需要从mongodb中的数组对象值求和 [英] Need to sum from array object value in mongodb
问题描述
如果该值存在,我正在尝试计算总值.但是查询无法100%工作.所以有人可以帮助我解决这个问题.这是我的样本文件.我附上了两个文件.请这些文件和找出最佳解决方案 文件:1
I am trying to calculate total value if that value exits. But query is not working 100%. So can somebody help me to solve this problem. Here my sample document. I have attached two documents. Please these documents & find out best solution Document : 1
{
"_id" : 1"),
"message_count" : 4,
"messages" : {
"data" : [
{
"id" : "11",
"saleValue": 1000
},
{
"id" : "112",
"saleValue": 1400
},
{
"id" : "22",
},
{
"id" : "234",
"saleValue": 111
}
],
},
"createdTime" : ISODate("2018-03-18T10:18:48.000Z")
}
文档:2
{
"_id" : 444,
"message_count" : 4,
"messages" : {
"data" : [
{
"id" : "444",
"saleValue" : 2060
},
{
"id" : "444",
},
{
"id" : 234,
"saleValue" : 260
},
{
"id" : "34534",
}
]
},
"createdTime" : ISODate("2018-03-18T03:11:50.000Z")
}
所需的输出:
{
total : 4831
}
我的查询:
db.getCollection('myCollection').aggregate([
{
"$group": {
"_id": "$Id",
"totalValue": {
$sum: {
$sum: "$messages.data.saleValue"
}
}
}
}
])
因此,请尽可能帮助我解决此问题.预先感谢
So please if possible help me to solve this problem. Thanks in advance
推荐答案
由于汇总了集合中的所有文档,因此无法正常工作;您要对常量"_id": "tempId"
进行分组,则只需通过添加$
来引用正确的键即可:
It's not working correctly because it is aggregating all the documents in the collection; you are grouping on a constant "_id": "tempId"
, you just need to reference the correct key by adding the $
as:
db.getCollection('myCollection').aggregate([
{ "$group": {
"_id": "$tempId",
"totalValue": {
"$sum": { "$sum": "$messages.data.value" }
}
} }
])
本质上是聚合操作的单阶段管道版本,带有一个额外的字段,该字段在组管道之前保存求和表达式,然后将该字段称为
which in essence is a single stage pipeline version of an aggregate operation with an extra field that holds the sum expression before the group pipeline then calling that field as the $sum
operator in the group.
由于 $sum
$group
阶段以及在 $sum
返回表达式列表的总和.表达式"$messages.data.value"
返回数字[120, 1200]
的列表,然后将其用作
The above works since $sum
from MongoDB 3.2+ is available in both the $project
and $group
stages and when used in the $project
stage, $sum
returns the sum of the list of expressions. The expression "$messages.data.value"
returns a list of numbers [120, 1200]
which are then used as the $sum
expression:
db.getCollection('myCollection').aggregate([
{ "$project": {
"values": { "$sum": "$messages.data.value" },
"tempId": 1,
} },
{ "$group": {
"_id": "$tempId",
"totalValue": { "$sum": "$values" }
} }
])
这篇关于需要从mongodb中的数组对象值求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!