在聚合和乘法期间合并2个文档

问题描述 投票:0回答:2

我有以下记录:

{
   "_id" : ObjectId("5a377b895a2840568b1034d5"),
   "reportId" : 1234,
   "quantity" : 346
},
{
  "_id" : ObjectId("5a377b935a2840568b1034d6"),
  "reportId" : 1234,
  "users" : 96
},
{
  "_id" : ObjectId("5a377ba35a2840568b1034d7"),
  "reportId" : 2345,
  "quantity" : 566    
},
{
  "_id" : ObjectId("5a377bac5a2840568b1034d8"),
  "reportId" : 2345,
  "users" : 66
}

我希望最终输出是这样的:

{'reportId': 1234, 'total':quantity * users}

换句话说,我希望总数是用户和数量的乘积

我尝试了以下方法:

db.test1.aggregate([ 
{'$group':
  { '_id':'$reportId', 
    'total':{'$multiply':['$users','$quantity']}
  }
}])

这给出了以下错误:

assert: command failed: {
    "ok" : 0,
    "errmsg" : "The $multiply accumulator is a unary operator",
    "code" : 40237,
    "codeName" : "Location40237"
} : aggregate failed

接下来我尝试了这个:

db.test1.aggregate([ {
'$group':
         { '_id':'$reportId', 
           'document':{'$push':{'reportId':'$reportId', 
                       'quantity':'$quantity','users':'$users'}}}},
{'$unwind':'$document'}])

这给了我:

{ "_id" : 2345, "document" : { "reportId" : 2345, "quantity" : 566 } }
{ "_id" : 2345, "document" : { "reportId" : 2345, "users" : 66 } }
{ "_id" : 1234, "document" : { "reportId" : 1234, "quantity" : 346 } }
{ "_id" : 1234, "document" : { "reportId" : 1234, "users" : 96 } }

我的目标是合并两个记录并应用乘法。

是否有可能在mongoDB聚合中执行此操作而不是获得中间答案并循环部分结果并完成工作?

python mongodb aggregation-framework pymongo multiplying
2个回答
3
投票

你几乎弄错了。我做了这个解决方案来组合两个字段的值:

db.test1.aggregate([
    {"$group":{
        "_id":"$reportId",
        "qtd":{$sum:"$quantity"},
        "usrs":{$sum:"$users"}
    }},
    {"$project":{
        "_id":0,
        "reportId":"$_id",
        "total":
            {$multiply:["$qtd","$usrs"]}
    }}
])

希望我的回答很有帮助。


3
投票

你几乎拥有它,$group是一个很好的方法来做到这一点。这样的事情应该有效。

db.test1.aggregate([
    {"$group":
        {
            "_id": "$reportId",
            "usr": {"$sum": "$users"},
            "qty": {"$sum": "$quantity"}
        }
    },
    {"$project":
         {
             "_id": 0,
             "reportId": "$_id",
             "total": {"$multiply": ["$usr", "$qty"]}
         }}
])

首先,我们将所有usersquantity组合起来,然后将它们相乘。在group阶段,您需要累积所需的指标。

© www.soinside.com 2019 - 2024. All rights reserved.