如何在MongoDB中聚合嵌套文档?
要在MongoDB中聚合嵌套文档,可以使用$group。首先让我们创建一个包含文档的集合-
> db.aggregateDemo.insertOne(
... {
... "ProductInformation": [
... {
... "Product1": [
... {
... Amount: 50
... },
... {
... Amount: 90
... },
... {
... Amount: 30
... }
... ]
... },
... {
... "Product1": [
... {
... Amount: 200
... },
... {
... Amount: 30
... },
... {
... Amount: 40
... }
... ]
... },
... {
... "Product1": [
... {
... Amount: 150
... },
... {
... Amount: 190
... },
... {
... Amount: 198
... }
... ]
... }
...
... ]
... });
{
"acknowledged" : true,
"insertedId" : ObjectId("5e04df58150ee0e76c06a04d")
}
> db.aggregateDemo.insertOne(
... {
... "ProductInformation": [
... {
... "Product1": [
... {
... Amount: 100
... },
... {
... Amount: 1002
... },
... {
... Amount: 78
... }
... ]
... },
... {
... "Product1": [
... {
... Amount: 75
... },
... {
... Amount: 400
... },
... {
... Amount: 600
... }
... ]
... },
... {
... "Product1": [
... {
... Amount: 700
... },
... {
... Amount: 500
... },
... {
... Amount: 600
... }
... ]
... }
...
... ]
... });
{
"acknowledged" : true,
"insertedId" : ObjectId("5e04df93150ee0e76c06a04e")
}以下是在find()方法的帮助下显示集合中所有文档的查询-
> db.aggregateDemo.find().pretty();
这将产生以下输出-
{
"_id" : ObjectId("5e04df58150ee0e76c06a04d"),
"ProductInformation" : [
{
"Product1" : [
{
"Amount" : 50
},
{
"Amount" : 90
},
{
"Amount" : 30
}
]
},
{
"Product1" : [
{
"Amount" : 200
},
{
"Amount" : 30
},
{
"Amount" : 40
}
]
},
{
"Product1" : [
{
"Amount" : 150
},
{
"Amount" : 190
},
{
"Amount" : 198
}
]
}
]
}
{
"_id" : ObjectId("5e04df93150ee0e76c06a04e"),
"ProductInformation" : [
{
"Product1" : [
{
"Amount" : 100
},
{
"Amount" : 1002
},
{
"Amount" : 78
}
]
},
{
"Product1" : [
{
"Amount" : 75
},
{
"Amount" : 400
},
{
"Amount" : 600
}
]
},
{
"Product1" : [
{
"Amount" : 700
},
{
"Amount" : 500
},
{
"Amount" : 600
}
]
}
]
}这是汇总嵌套文档的查询-
> db.aggregateDemo.aggregate([
... {
... $unwind:"$ProductInformation"
... },
... {
... $unwind:"$ProductInformation.Product1"
... },
... {
... $group:{
... _id:null,
... MaximumAmount:{
... $max:"$ProductInformation.Product1.Amount"
... }
... }
... }
... ]);这将产生以下输出-
{ "_id" : null, "MaximumAmount" : 1002 }热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短