i have a collection placements, each record has fields: placement_id, program_id, category, ... i need to find all placements what has program_id = 3 or 5 and only return a list of placement_id.
when i tried this command:
db.placements.find({program_id:{$in: [3, 5]}}, {placement_id:1, _id:0})
i got records:
{ "placement_id" : 196 }
{ "placement_id" : 197 }
{ "placement_id" : 198 }
...
is there any way to return just:
[196, 197, 198...]
You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});
In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents.
When you use methods such as find() or findOne() in MongoDB, by default you get the whole document returned. And if you use projections, you can return specific key/value pairs. But what if you only want the value? You can extract the value of a field by appending that field's name to your query when using findOne() .
The cursor from find()
is going to yield JSON documents, no matter what.
But you can extract the values you want. Something like this perhaps :
get_placement_id = function(doc) { return doc.placement_id; }
db.placements.find({program_id:{$in: [3, 5]}}, {placement_id:1, _id:0}).map( get_placement_id )
==>
[ 196, 197, 198, ... ]
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