How to do field selection on find() in the mongodb native driver?

前端 未结 4 1080
遇见更好的自我
遇见更好的自我 2021-02-19 07:52

I am using the mongodb native driver for node.js and can\'t get to work the field selection. What I want to do is to limit fields to name. I do not want the \'last\' in the outp

相关标签:
4条回答
  • 2021-02-19 08:06

    The field selection argument to find is an object, not an array. And you can't mix field inclusion and exclusion (except for _id), so it should be:

    db.collection("test").find({}, {'name': true}).toArray(function(err, results) {
        console.dir(results);
    });
    
    0 讨论(0)
  • 2021-02-19 08:09

    If you are using latest mongodb 3.0 nodejs driver, then try this code:

    db.collection('test').find({}).project({name: 1, last: 1}).toArray();
    
    0 讨论(0)
  • 2021-02-19 08:23

    Omit the array:

    db.collection("test").find({},{'name':true,'last':false}).toArray(function(err, results) {
        console.dir(results);
    });
    
    0 讨论(0)
  • 2021-02-19 08:27

    The recommended way of doing this in v3.0 is with the projection field in the options object:

    db.collection('test').find({}, {projection: {name: 1}}).toArray()
    

    As mentioned in the accepted answer, you still cannot mix inclusion and exclusion.

    See: http://mongodb.github.io/node-mongodb-native/3.0/api/Collection.html#find

    0 讨论(0)
提交回复
热议问题