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 } ] }
You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});
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.
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});
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!
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