mongodb的node.js Driver查询中指定返回字段有以下几种方式:
//最新版推荐使用,mongodb@3测试可以用
db.collection('blogs').find({},{projection:{author:0,comments:0},sort:{author:-1}}).limit(2).toArray(function (err,data) {})
//在mongodb@2 和 mongodb@3都可以使用
db.collection('blogs').find({},{fields:{author:0,comments:0},sort:{author:-1}}).limit(2).toArray(function (err,data) {})
//在mongodb@2.0.31中可以使用
db.collection('blogs').find({},{author:0,comments:0},{sort:{author:-1}}).limit(2).toArray(function (err,data) { })
总结:根据自己的mongodb driver版本选择使用方法
因为我项目用到的mongodb driver版本比较老(@2.0.31),projection字段不支持,选用的fields字段解决。第3三种方法在最新版中已经不再被支持,尽量不要用了。
参考文档:http://mongodb.github.io/node-mongodb-native/3.0/api/Collection.html#find
https://www.npmjs.com/package/mongodb