5

I am trying to return only one field sessions from a document.

I'm using the current query (it returns the entire document):

yield users.findOne({
    '_id': id // var id holds object id ObjectId("560ae1dc53cb3222679430f1")
}, {
    '_id': 0, // <--- being ignored
    'sessions': 1 // <--- being ignored
});

I tried in mongo shell and this works as it should:

db.users.find({"_id":ObjectId("560ae1dc53cb3222679430f1")},{"sessions":1,"_id":0}).pretty() // <--- works

I'm currently using co-monk which is based off of mongoskin. So it should work.

basickarl
  • 37,187
  • 64
  • 214
  • 335

3 Answers3

11

Not made clear in the documentation, but there is an explicit key name syntax to the "options" object :

yield users.findOne({ '_id': id }, { 'fields': { '_id': 0, 'sessions': 1  }});

So it works a bit differently to the MongoDB shell API. The same applies for other options such as sort.

Blakes Seven
  • 49,422
  • 14
  • 129
  • 135
  • Wow it works. Can you link where you found this out, would love to read the rest of it (will be needing it). – basickarl Sep 30 '15 at 00:13
  • Found out that I should of been looking at https://github.com/christkv/node-mongodb-native as mongoskin wraps it – basickarl Sep 30 '15 at 00:38
6

The accepted answer didn't work in my case, so I went digging through the docs and this is what I found for the fields option: Deprecated Use options.projection instead, and got the respective warning in the console. Chaining in .project() as with .find() didn't work for .findOne() in my case, so it has to be in the options using projection:

yield users.findOne({
    '_id': id 
}, { projection: { //projection rather than fields
    '_id': 0,
    'sessions': 1 }
});

Here it is: mongodb.github.io/node-mongodb-native

Tomás Metcalfe
  • 163
  • 1
  • 4
0

2022 update

You have to use projection in latest update.
Reference: https://www.mongodb.com/docs/drivers/node/current/quick-reference/

Here is a sample code for this question.

const ObjectId = require('mongodb').ObjectId;

var query = { _id: ObjectId('your search object id here') };
var options = { projection: { sessions: 1, _id: 0 } };

users.findOne(query, options);
Dinith Rukshan Kumara
  • 638
  • 2
  • 10
  • 19