【问题标题】:mongoDB updateMany with upsert true and $in in where conditionmongoDB updateMany with upsert true 和 $in 在 where 条件
【发布时间】:2018-04-07 11:28:18
【问题描述】:

如果 where 条件不满足 upsert true,如何插入多条记录,例如考虑下面的查询,

db.getCollection('Llog').updateMany(
{"macID" : {$in : [1,2]}}, 
{$push : { "logDetails" : { $each : [{ wk: 15, score: 15 }] }}}, 
{upsert : true}
) 

在我的 where 条件下,我使用“$in”[1,2],如果有 macID 的记录:1,那么我应该使用“logDetails”更新记录,如果我没有找到 macID 的记录:2,那么我需要插入记录。如果我发现两条记录都存在,则更新两条记录,或者如果我发现两条记录都不存在,则插入。

对于上面的代码,如果两者都不存在,则插入如下记录

{
    "_id" : ObjectId("59f18e68c19f798cffa406a8"),
    "logDetails" : [ 
        {
            "wk" : 15,
            "score" : 15
        }
    ]
}

例如,如果 macId : 1 可用,那么我执行第一组 updateMany 代码,那么它应该更新 macID : 1 并插入 macID : 2,但它不会插入 macID : 2 但它会更新 macID : 1。

【问题讨论】:

  • 您目前不能这样做。而不是.updateMany(),您向.bulkWrite() 发出两个操作,每个"upsert" 设置为true。当前的 DSL 无法确定 12 中的哪一个当前正在作为“upsert”进行操作。上面可能有一个 JIRA,但我现在找不到它。

标签: mongodb


【解决方案1】:

{"macID" : {$in : [1,2]}} 并不意味着您正在搜索两个文档("macID" : 1"macID" : 2),这意味着您正在搜索任何具有 macID 等于 12 的文档。

所以upsert: true 告诉 MongoDB 只创建一个文档(而不是两个)。

您必须提供多个更新请求(使用bulkWriteupdateOne 而不是updateMany)。

【讨论】:

  • 好的,我们该如何解决这个问题?有没有其他办法?
  • @user 使用bulkWriteupdateOne(我更新了我的答案)
  • 任何寻找实现的人,check this answer out
猜你喜欢
  • 2015-11-30
  • 1970-01-01
  • 2019-05-12
  • 2019-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多