zoukankan      html  css  js  c++  java
  • MongoDB投影有$slice如何只显示该字段

    简单的投影

    稍微用过MongoDB的都知道,投影很简单,就直接

    db.student.find({_id:ObjectId('5a5085aed8f10c1a6cc0395b')},{comments: 1})
    

    添加$slice的投影

    然而,当我要给comments分页($slice)如何做呢?

    错误的做法

    以下给出了错误的做法

    db.student.find({_id:ObjectId('5a5085aed8f10c1a6cc0395b')},{comments: 1, comments:{$slice:[0,1]}})
    

    这样写的话,就只有分页,然后字段显示全部

    原因
    对象中,同名字段,后者会覆盖前者。所以{comments: 1, comments: {$slice:[0,1]}}中实际生效的只有comments:{$slice:[0,1]}
    同理,如果两个调换位置变成{comments: {$slice:[0,1]}, comments: 1},那么实际生效的就是 comments: 1没有分页

    正确的写法

    多写一个随意的字段(不跟已有的字段已有)可以做到,具体原理求告知

    db.student.find({_id:ObjectId('5a5085aed8f10c1a6cc0395b')}, {comments:{$slice:[0,1]},  xxx:1})
    

    简单的投影

    稍微用过MongoDB的都知道,投影很简单,就直接

    db.student.find({_id:ObjectId('5a5085aed8f10c1a6cc0395b')},{comments: 1})
    

    添加$slice的投影

    然而,当我要给comments分页($slice)如何做呢?

    错误的做法

    以下给出了错误的做法

    db.student.find({_id:ObjectId('5a5085aed8f10c1a6cc0395b')},{comments: 1, comments:{$slice:[0,1]}})
    

    这样写的话,就只有分页,然后字段显示全部

    原因
    对象中,同名字段,后者会覆盖前者。所以{comments: 1, comments: {$slice:[0,1]}}中实际生效的只有comments:{$slice:[0,1]}
    同理,如果两个调换位置变成{comments: {$slice:[0,1]}, comments: 1},那么实际生效的就是 comments: 1没有分页

    正确的写法

    多写一个随意的字段(不跟已有的字段已有)可以做到

    db.student.find({_id:ObjectId('5a5085aed8f10c1a6cc0395b')}, {comments:{$slice:[0,1]},  xxx:1})
    

    _id怎么样都会显示,随意乱写不好,统一用_id吧

    db.student.find({_id:ObjectId('5a5085aed8f10c1a6cc0395b')}, {comments:{$slice:[0,1]},  _id:1})
    

    原理

    被slice的字段一定会显示,加上其他的字段(例如_id),当然就会进行投影筛选~

  • 作者:小新是也
  • 链接:http://www.cnblogs.com/chenchuxin
  • 来源:博客园
  • 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
查看全文
  • 相关阅读:
    基于Lucene 4.x的ikanalyzer
    scala实现HighCharts生成的SVG图像下载
    使用solrj和EasyNet.Solr进行原子更新
    Bootstrap 2.3.0自定Grid布局
    无法删除打印机Failed to remove driver ZDesigner ZT210300dpi ZPL. Failed to remove package zdesigner.inf. Driver package is in use.
    彩云披月镜,委蛇藏花芯。朝辞浮云晓,元初破日衣。
    python browser.find_element_by 方法过期browser.find_element_by_tag_name;browser.find_element_by_class_name;browser.find_element_by_id;browser.find_element_by_name;
    c++中按位取反
    typedef用法总结
    Visual C++开发工具与调试技巧整理
  • 原文地址:https://www.cnblogs.com/chenchuxin/p/8254149.html
  • Copyright © 2011-2022 走看看