Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return only a single property "_id"

Tags:

mongodb

I would like to know if there is a way to return only the _id, user_id and total without the items subdocument.

{     "_id" : 122,     "user_id" : 123456,     "total" : 100,     "items" : [             {                     "item_name" : "my_item_one",                     "price" : 20             },             {                     "item_name" : "my_item_two",                     "price" : 50             },             {                     "item_name" : "my_item_three",                     "price" : 30             }     ] } 
like image 391
user1409708 Avatar asked Jun 14 '12 04:06

user1409708


People also ask

How do I return a specific field in MongoDB?

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

How do I find one record in MongoDB?

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.


2 Answers

The second parameter of find lets you select fields. So you can use this (note that the _id field is always selected anyway):

db.mycollection.find({}, {"user_id": 1, "total": 1}); 

You can also exclude certain fields, so this would be equivalent:

db.mycollection.find({}, {"items": 0}); 

You can exclude _id field by doing:

db.mycollection.find({}, {"user_id": 1, "_id": 0}); 
like image 82
McGarnagle Avatar answered Sep 28 '22 17:09

McGarnagle


What I was looking for is returning a list of ids, so return only _id but as an array for all documents. I did it as such:

db. mycollection.distinct("_id", {}) 

The first parameter is your distict fields, and second is your query. More on distinct here. Hopefully this helps someone with a similar requirement. Cheers!

like image 43
radtek Avatar answered Sep 28 '22 17:09

radtek