更新处理重复项并增加运算符的查询

时间:2017-11-22 12:05:59

标签: javascript mongodb

背景:

  1. 我有一个名为alerts的集合的更新查询,每个集合运行 时间a"流动"收到了。
  2. 我在提醒的文档中有一组对象叫做 blacklistedCommunication
  3. 会发生什么:

    当新流量到达时,如果流量alertsclient_addr尚未出现,则server_addr文档仅更新 blacklistedCommuication。与此同时,如果我们确实找到了重复项,那么它应该只增加flowCount

    当前查询:

    以下更新查询用于将新对象推送到blacklistedCommunication对象(如果它尚未出现)。 但是,如果确实存在,则不会更新flowCount

    如何将此逻辑合并到查询中?我是否需要在重复的情况下编写单独的更新查询?

    alerts.update({
           alertLevel: "orgLevelAlert",
           alertCategory: "blacklistedServersViolationAlert",
           alertState: "open",
           'blacklistedCommunication.client': {
               $ne: flow.netflow.client_addr
           },
           // 'blacklistedCommunication.server': {
           //     $ne: flow.netflow.server_addr
           // }  
        }, {
           $set: {
               "misc.updatedTime": new Date()
           },
           $inc: {
               flowCount: 1
           },
           $push: {
               blacklistedCommunication: {
                   client: flow.netflow.client_addr,
                   server: flow.netflow.server_addr
               }
           }
        });
    

1 个答案:

答案 0 :(得分:1)

您可以使用$addToSet代替$push。它将确保{client:*,server:*}内的唯一blacklistedCommunication对象,并始终更新flowCount

alerts.update({
   alertLevel: "orgLevelAlert",
   alertCategory: "blacklistedServersViolationAlert",
   alertState: "open"
}, {
   $set: {
       "misc.updatedTime": new Date()
   },
   $inc: {
       flowCount: 1
   },
   $addToSet: {
       blacklistedCommunication: {
           client: flow.netflow.client_addr,
           server: flow.netflow.server_addr
       }
   }
});
相关问题