我正在使用node.js的mongodb本机驱动程序,无法进行字段选择.我想要做的是限制字段名称.我不希望输出中的'last'.
我这样做:
db.collection("test").find({},[{'name':true,'last':false}]).toArray(function(err, results) { console.dir(results); });
但日志打印:
[ { _id: 524b53588aa4f388de1c2ddb }, { _id: 524b53548aa4f388de1c2dda } ]
所以name
输出中没有.
更新:我尝试过一个对象而不是数组 - 没有用.原因是混合包含和排除.你不能混合它.当我只有"name":true
它工作.
如果您使用的是最新的mongodb 3.0 nodejs驱动程序,请尝试以下代码:
db.collection('test').find({}).project({name: 1, last: 1}).toArray();
在v3.0中执行此操作的推荐方法是使用options对象中的投影字段:
db.collection('test').find({}, {projection: {name: 1}}).toArray()
如接受的答案中所述,您仍然无法混合包含和排除.
请参阅:http://mongodb.github.io/node-mongodb-native/3.0/api/Collection.html#find
字段选择参数to find
是一个对象,而不是一个数组.并且您不能混合使用字段包含和排除(除了_id
),因此它应该是:
db.collection("test").find({}, {'name': true}).toArray(function(err, results) { console.dir(results); });