简体   繁体   English

MongoDB-多个集合中的$ sum

[英]MongoDB - $sum in multiple collections

I have many collections. 我有很多收藏。 The view of these collections is the same as the JSON. 这些集合的视图与JSON相同。 What I want to do is to collect the collections according to their id and create a collection. 我要做的是根据其ID收集集合并创建一个集合。 How can I do it? 我该怎么做?

A.json A.json

{
    "_id" : ObjectId("58455d2d506c1cab1c82152c"),
    "value" : 515835.0
}
{
    "_id" : ObjectId("58455d2d506c1cab1c82153c"),
    "value" : 6621696.0
}

B.json B.json

{
    "_id" : ObjectId("58455d2d506c1cab1c82152c"),
    "value" : 2118.0
}
{
    "_id" : ObjectId("58455d2d506c1cab1c82153c"),
    "value" : 1190.0
}
{
    "_id" : ObjectId("423232d2d506c1cab1c1232c"),
    "value" : 10.0
}

Collect in A collection, id: 1, collection B id: 1 if it matches. 在A集合中收集,ID:1,集合B ID:1(如果匹配)。

A in the collection, id: 2, if you are not in any collection, you are only showing that value. 集合ID中的A:2,如果您不在任何集合中,则仅显示该值。

In the last collection I have collected, I want to make a collection of objects and id in pairs. 在我收集的最后一个收集中,我想成对收集对象和ID。

Result.json Result.json

{
    "_id" : ObjectId("58455d2d506c1cab1c82152c"),
    "value" : 517953.0 // A.value + B.value
}
{
    "_id" : ObjectId("58455d2d506c1cab1c82153c"),
    "value" : 6633596.0 // A.value + B.value
}
{
    "_id" : ObjectId("423232d2d506c1cab1c1232c"),
    "value" : 10.0 // B.value (A.value : null)
}

i want this for multiple collections. 我想要这个为多个集合。

For 1-0/1 relation given in the example you can use $lookup as following: 对于示例中给出的1-0 / 1关系,可以使用$ lookup ,如下所示:

db.B.aggregate([
    {$lookup: {
        from: "A",
        localField: "_id",
        foreignField: "_id",
        as: "a"
    }},
    {$unwind: {path: "$a", preserveNullAndEmptyArrays: true}},
    {$project: {
        value: {$add: ["$value", {$ifNull: ["$a.value", 0 ]}]}
    }}
]);

It does ignore any documents in A, which have no corresponding documents in B, ie result have the same number of documents as in collection B. 它的确会忽略A中的任何文档,而B中没有相应的文档,即结果与集合B中的文档数量相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM