我正在使用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
它才有效。
答案 0 :(得分:17)
如果您使用的是最新的mongodb 3.0 nodejs驱动程序,请尝试以下代码:
db.collection('test').find({}).project({name: 1, last: 1}).toArray();
答案 1 :(得分:15)
find
的字段选择参数是一个对象,而不是一个数组。并且您不能混合字段包含和排除(_id
除外),因此它应该是:
db.collection("test").find({}, {'name': true}).toArray(function(err, results) {
console.dir(results);
});
答案 2 :(得分:8)
在v3.0中执行此操作的推荐方法是使用选项对象中的投影字段:
db.collection('test').find({}, {projection: {name: 1}}).toArray()
如接受的答案中所述,您仍然无法混合包含和排除。
请参阅:http://mongodb.github.io/node-mongodb-native/3.0/api/Collection.html#find
答案 3 :(得分:0)
省略数组:
db.collection("test").find({},{'name':true,'last':false}).toArray(function(err, results) {
console.dir(results);
});