Why can I not be able to return only one field using "findOne()"? In the code below, all fields are returned. I also tried "find()", but still not working. Can someone tell me whether I made a mistake or what?
In this case, I want to return only "info" field
const mongodb = require('mongodb').MongoClient
...
db_main.collection('info').findOne({ _id: '123456789' }, { info: 1 }, function(err, result) {
console.log(result)
})
The document look something like this:
_id: '123456789',
title: 'I love title',
content: 'content here',
info: {
date: '1/1/2018',
user: 'username'
}
findOne() method returns a Promise that resolves to the first document in the collection that matches the query. If no documents match the specified query, the promise resolves to null .
It looks like findOne() is only deprecated in the Javascript driver. Worse, MongoDB node driver uses findOne internally extensively. The change was made last year, as part of a series of commits carrying the helpful message "clean up docs".
MongoDB – FindOne() Method. The findOne() method finds and returns one document that matches the given selection criteria. If multiple documents satisfy the given query expression, then this method will return the first document according to the natural order which reflects the order of documents on the disk.
You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});
You are not using the projection option:
{projection: { info: true }}
The way you are doing
{info:1}
It means you are requesting to use an index on info (if it exist)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With