mongo投影:更新现有节点(如果存在)或添加新节点

时间:2019-10-30 12:06:16

标签: mongodb

{
    "apps_count" : [
        1,
        5,
        2
    ],
    "channels" : [
        "offline",
        "offline",
        "offline"
    ],
    "types" : [
        "STATEMENT",
        "STATEMENT",
        "STATEMENT"
    ],
    "division" : [
        "PROD",
        "NONE",
        "NONE"
    ],
    "scan_status" : [
        1,
        0,
        1
    ],
    "applications" : [
        [{}],
        [{},{},{},{},{}],
        [{},{}]
    ]
}

几组分组之后,我得到了上述格式数据。对于脱机渠道和声明类型,我已扫描(即1)和未扫描(即0)应用程序。对于扫描,我总共有3个应用程序,对于未扫描,我有5个应用程序。

我想通过循环条件类型为离线通道和状态类型为投影一部分的通道来获取格式数据。 (类型,渠道,部门不限于以上,我有不同的组合)

output: 
{
    "offline_stmt" : {
                "scanned": {
                    "count" : 3,
                    "applications" : [{},{},{}] 
                },
                "non_scanned" : {
                    "count" : 5,
                    "applications" : [{},{},{},{},{}    ] 
                }
    }
}

我尝试过,但是我得到了重复的节点并覆盖了较旧的节点。我想更新if节点是否存在,就像第三个“离线”频道一样,我应该用累积计数和附加应用程序更新现有的扫描节点。

 $map: {
          input: "$channels",
          as: "channel",
          in: {
           $cond: [ { $and: [{$eq: ["$$channel", "Online"]}, { $eq: [{ $arrayElemAt: ["$types", {$indexOfArray: [ "$channels" , "$$channel" ] } ] },"STATEMENT"]} ] }, {
                                   "online_stmt" : {
                                           $cond: { if: { $eq: [{ $arrayElemAt: ["$scan_status", {$indexOfArray: [ "$channels" , "$$channel" ] } ] }, 1]}, then: {
                                               "scanned": {
                                                   "count" : { $arrayElemAt: ["$applications_count", {$indexOfArray: [ "$channels" , "$$channel" ] } ] },
                                                   "applications" : { $arrayElemAt: ["$applications", {$indexOfArray: [ "$channels" , "$$channel" ] } ]}
                                               }
                                           }, else: {
                                               "non_scanned" : {
                                                   "count" : { $arrayElemAt: ["$applications_count", {$indexOfArray: [ "$channels" , "$$channel" ] } ] },
                                                   "applications" : { $arrayElemAt: ["$applications", {$indexOfArray: [ "$channels" , "$$channel" ] } ]}
                                               }
                                           } }
                                       }
                                   } , {}]

0 个答案:

没有答案