igortp
igortp

Reputation: 179

MongoDB projection syntax

I'm writing a web application using NodeJs, and the most common syntax I use to project fields is:

db().collection("users").findOne(
    { name: "Igor" },
    { projection: { name: true, _id: false } }
);

It works well in the NodeJs environment. But then I was doing some checks through the shell, and this same query returns me an error:

//query
db.users.findOne({ name: "Igor" },{ projection:{ name: true, _id: false }})

//output
Error: error: {
    "ok" : 0,
    "errmsg" : "Cannot do exclusion on field _id in inclusion projection",
    "code" : 31254,
    "codeName" : "Location31254"
}

Then, I tried to find references to {projection: <field>: <true or false>} without success. I also didn't have better luck researching the error. Then I thought it could be a method from the NodeJs Driver, but I also didn't find anything in the docs.

Another behavior is that when I try to project the name on the mongo shell, the result is only the document _id.

//query    
db.users.findOne({ name: "Igor" },{ projection:{ name: true }})

//output    
{ "_id" : ObjectId("607469840eaf9097e49c10c3") }

To be clear about what would be the expected result, I would achieve that result by writing the following query:

db.users.findOne({name: "Igor"},{ name: true, _id: false })

Could someone enlighten me where I could read more about this projection property? Or this a deprecated one that for some reason is still working?

Upvotes: 0

Views: 1602

Answers (2)

ghiles ybeggazene
ghiles ybeggazene

Reputation: 275

 Photo.find({},{ book_id: 1, user_id: 1,  datetime: 1, userAgent: 1, createdAt: 1 })

Upvotes: 0

D. SM
D. SM

Reputation: 14480

The shell findOne method is documented here: https://docs.mongodb.com/manual/reference/method/db.collection.findOne/

Projection is the second positional argument, you are sending it as an options hash which is incorrect.

Upvotes: 1

Related Questions