I have a collection of this kind of document:
{
"_id": {
"$oid": "6047b855a6ce7d24a4cda693"
},
"address": "Bergamo, Via S. Bernardino, 57",
"products": [{
"productId": "6047b855a6ce7d24a4cda694",
"qty": 7,
"alarmTh": 5
}, {
"productId": "6047b855a6ce7d24a4cda695",
"qty": 5,
"alarmTh": 5
}],
"_class": "warehouseservice.team2.warehouseservice.models.Warehouse"
}
I need to find a product with a specific productId. Let's say that I want the object with Id = 6047b855a6ce7d24a4cda694, the result that I want is the following:
{
"productId": "6047b855a6ce7d24a4cda694",
"qty": 7,
"alarmTh": 5
}
I tried with this:
db.warehouse.find({"products.productId": "6047b855a6ce7d24a4cda694"}, {"products.$": 1, _id: 0})
but this returns:
{ products: [ { productId: '6047b855a6ce7d24a4cda694', qty: 7, alarmTh: 5 } ] }
so an array, but I want only one single object.
Thanks
You can use the aggregation pipeline and $replaceRoot :
db.collection.aggregate([
{
"$match": {
"products.productId": "6047b855a6ce7d24a4cda694"
}
},
{
"$project": {
products: {
"$first": "$products"
}
}
},
{
"$replaceRoot": {
"newRoot": "$products"
}
}
]);
Output:
[
{
"alarmTh": 5,
"productId": "6047b855a6ce7d24a4cda694",
"qty": 7
}
]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.