Reputation: 9738
I want to select an object within an array with id
condition. In the below img i want to select [0]
.
db.users.find({"injury._id": ObjectId("537233061845d2ec10000071")})
Thankx for Help.
Upvotes: 1
Views: 49
Reputation: 151112
I'm guessing here that you want to only see the selected array element in the document you are searching for. Use projection:
db.users.find(
{ "injury._id": ObjectId("537233061845d2ec10000071")},
{ "injury.$": 1 }
)
That just returns the matching element rather than all of them.
If you expect more than one match ( unlikely with an ObjectId, but for future reference ) then use the .aggregate()
method instead:
db.users.aggregate([
// Match documents first, helps reduce the pipeline
{ "$match": {
"injury._id": ObjectId("537233061845d2ec10000071")
}},
// Unwind the array
{ "$unwind": "$injury" },
// Actually match the elements
{ "$match": {
"injury._id": ObjectId("537233061845d2ec10000071")
}},
// Group back if you really want arrays
{ "$group": {
"_id": "$_id",
"injury": { "$push": "$injury" },
// and use "$first" for any other fields
}}
])
So now you know what to do when you come up against that one as well.
Upvotes: 2