如何对 MongoDB 中的嵌套文档进行聚合?\n
要对 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 }
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP