Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongodb how to return list of value only from find query

Tags:

mongodb

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...]
like image 340
user468587 Avatar asked Apr 01 '14 14:04

user468587


People also ask

How do I get only certain fields in MongoDB?

You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});

What does find () do in MongoDB?

In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents.

How do I return a value in MongoDB?

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() .


1 Answers

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, ... ]
like image 179
dampier Avatar answered Nov 15 '22 18:11

dampier