根据数组值聚合以求和不同 MongoDB 文档中的值?


为此,请在 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 }

更新于: 31-Mar-2020

697 次浏览

开启你的 事业

完成课程获得认证

开始
广告
© . All rights reserved.