如何根据数组值对不同 MongoDB 文档中的值进行聚合?
mongodbdatabasebig data analytics更新于 2026/1/10 7:37:17
为此,请使用 MongoDB 中的 aggregate() 方法。首先,我们创建一个包含文档的集合。 −
> db.demo126.insertOne(
... {
... "StudentDetails" : {
... "Number" : 1,
... "OtherDetails" : [
... {
... "Name" : "Chris",
... "Score" : 55
...
... }
... ].. }}
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e304b3068e7f832db1a7f56")
}
>
>
> db.demo126.insertOne(
... {
... "StudentDetails" : {
...
... "Number" : 2,
... "OtherDetails" : [
... {
... "Name" : "Chris",
... "Score" : 35
...
... },
... {
... "Name" : "David",
... "Score" : 87
... }
...
... ]
... }}
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e304b3068e7f832db1a7f57")
}
借助 find() 方法显示集合中的所有文档 −
> db.demo126.find();
这将产生以下输出 −
{ "_id" : ObjectId("5e304b3068e7f832db1a7f56"), "StudentDetails" : { "Number" : 1, "OtherDetails" : [ { "Name" : "Chris", "Score" : 55 } ] } }
{ "_id" : ObjectId("5e304b3068e7f832db1a7f57"), "StudentDetails" : { "Number" : 2, "OtherDetails" : [ { "Name" : "Chris", "Score" : 35 }, { "Name" : "David", "Score" : 87 } ] } }
以下是基于数组值进行聚合的查询 −
> db.demo126.aggregate([
... {
... $unwind:"$StudentDetails.OtherDetails"
... },
... {
... $group:{
... _id:"$StudentDetails.OtherDetails.Name",
... quantity:{
... $sum:"$StudentDetails.OtherDetails.Score"
... }
... }
... }
... ])
这将产生以下输出 −
{ "_id" : "David", "quantity" : 87 }
{ "_id" : "Chris", "quantity" : 90 }

