Reputation: 1323
i have a follwing structure in mongo db
{
"_id" : ObjectId("58e8d3323fe482ef368b4567"),
"productId" : "poe10001134",
"batchdetails" : [
{
"batchidId" : "BD0166",
"batchno" : "BbfN-1444-SBRPX"
},
{
"batchidId" : "BD0167",
"batchno" : "Bff-8444-kfkff"
},
{
"batchidId" : "BD01447",
"batchno" : "Bff-8415-kfkff"
}
]
}
i want to achieve following result
"productId" : "poe10001134"
"batchno" : "Bff-8415-kfkff"
when i execute following query
db.getCollection('table').findOne( {"batchdetails.batchidId" : "BD01447"},{productId:1,"batchidId.batchno":1})
it returns all the batch no
"productId" : "poe10001134"
"batchno" : "BbfN-1444-SBRPX"
"batchno" : "Bff-8444-kfkff"
"batchno" : "Bff-8415-kfkff"
Upvotes: 0
Views: 300
Reputation: 2639
Do it like this:
db.getCollection('table').findOne( {"batchdetails.batchidId" : "BD01447"},
{productId:1,"batchidId.batchno.$":1})
The $
in the projection contains the index of the batchno
array element that was matched in the query.
Upvotes: 1