javascript - 更新处理重复项和增量运算符的查询

标签 javascript mongodb

背景:

  1. 我有一个名为 alerts 的集合更新查询,该查询运行每个 收到“流”的时间。
  2. 我的警报文档中有一个对象数组,名为 列入黑名单的通讯

应该发生什么:

当新流到达时,如果该流的 client_addrserver_addr 则更新 alerts 文档尚未出现在 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
           }
       }
    });

最佳答案

您可以使用$addToSet而不是$push。它将确保 blacklistedCommunication 中唯一的 {client:*,server:*} 对象,并且始终更新 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
       }
   }
});

关于javascript - 更新处理重复项和增量运算符的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47434299/

相关文章:

javascript - json数组值没有传回jquery

javascript - 在 extJS 4 中增加 htmlEditor 的高度

javascript - 隐藏空列后保持表格 100% 宽度

javascript - 使用Ajax读取远程文档的变量值

python - Pymongo MongoClient : if you put a database in via URI, 如何将其恢复?

node.js - 为什么当我第二次运行测试时,Mongoose 中会出现错误 "Cannot overwrite model once compiled"?

python - MongoDB 插入速度权衡

javascript - EJS Javascript 中分解语句的规则是什么?

javascript - Mongoose 架构 : Forcing an array of objects to be created

javascript - MongoDB 选择和连接字段