Mongodb not returning specific fields
Asked Answered
D

3

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.

Distracted answered 29/9, 2015 at 23:59 Comment(0)
P
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.

Pneumodynamics answered 30/9, 2015 at 0:11 Comment(2)
Wow it works. Can you link where you found this out, would love to read the rest of it (will be needing it).Distracted
Found out that I should of been looking at github.com/christkv/node-mongodb-native as mongoskin wraps itDistracted
E
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

Eroticism answered 4/2, 2019 at 18:34 Comment(0)
L
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);
Lactobacillus answered 3/8, 2022 at 21:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.