我有一个mongo收藏(商店详细信息),如下所示...
{
_id: "",
storeName: "store1",
items: [
{
itemName: "mongo",
itemPrice: 20,
itemAvailablity: 100
},
{
itemName: "apples",
itemPrice: 50,
itemAvailablity: 70
}
]
},
{
_id: "",
storeName: "store2",
items: [
{
itemName: "banana",
itemPrice: 10,
itemAvailablity: 30
},
{
itemName: "apple",
itemPrice: 45,
itemAvailablity: 90
}
]
},
{
_id: "",
storeName: "store3",
items: [
{
itemName: "apple",
itemPrice: 10,
itemAvailablity: 30
},
{
itemName: "mongo",
itemPrice: 30,
itemAvailablity: 50
}
]
}
从以上数据中,我想获取特定的商品详细信息以及storeName。
如果我想从所有商店获取“ mongo”详细信息,那么我的预期输出将类似于
[
{
itemName: "mongo",
itemPrice: 20,
itemAvailablity: 100,
storeName: "store1"
},
{
itemName: "mongo",
itemPrice: 30,
itemAvailablity: 50,
storeName: "store3"
}
]
我尝试使用不同的mongo聚合查询,但没有得到预期的输出
有人可以帮助我
谢谢
答案 0 :(得分:2)
您可以使用以下汇总
db.collection.aggregate([
{ "$match": { "items.itemName": "mongo" }},
{ "$unwind": "$items" },
{ "$match": { "items.itemName": "mongo" }},
{ "$addFields": { "items.storeName": "$storeName" }},
{ "$replaceRoot": { "newRoot": "$items" }}
])
或者您可以这样做
db.collection.aggregate([
{ "$match": { "items.itemName": "mongo" }},
{ "$addFields": {
"items": {
"$map": {
"input": {
"$filter": {
"input": "$items",
"as": "item",
"cond": { "$eq": ["$$item.itemName", "mongo"]}
}
},
"as": "item",
"in": { "$mergeObjects": ["$$item", { "storeName": "$storeName" }] }
}
}
}},
{ "$unwind": "$items" },
{ "$replaceRoot": { "newRoot": "$items" }}
])
答案 1 :(得分:1)
您可以通过以下聚合来实现:
db.collection.aggregate([
{
$project: {
storeName: "$$CURRENT.storeName",
items: {
$filter: {
input: "$items",
as: "item",
cond: { $eq: ["$$item.itemName","mongo"] }
}
}
}
},
{ $unwind: "$items" },
{ $addFields: { "items.storeName": "$storeName"} },
{ $replaceRoot: { newRoot: "$items" }}
])
您可以看到它working here
答案 2 :(得分:0)
db.collection.aggregate(
// Pipeline
[
// Stage 1
{
$match: {
items: {
$elemMatch: {
"itemName": "mongo"
}
}
}
},
// Stage 2
{
$project: {
items: {
$filter: {
input: "$items",
as: "item",
cond: {
$eq: ["$$item.itemName", 'mongo']
}
}
},
storeName: 1
}
},
// Stage 3
{
$addFields: {
"items.storeName": '$storeName'
}
},
]
);