mongoDB updateMany with upsert true 和 $in in where 条件 [英] mongoDB updateMany with upsert true and $in in where condition

查看:73
本文介绍了mongoDB updateMany with upsert true 和 $in in where 条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How to insert many records if where condition does not meet with upsert true, for example consider below query,

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 那么我需要插入记录.如果我发现两个记录都存在则更新两个或者如果我发现两个记录都不存在则插入.

in my where condition i use "$in" [1,2], if there is record for macID : 1 then i should update the record with "logDetails", if i do not find record for macID : 2 then i need to insert record. If i find both records exist then update both Or if i find both records not exist then insert.

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

For the above code, it inserts record as below, if both are not exist

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

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

For example, if macId : 1 is available then i do the 1st set of updateMany code, then it should update macID : 1 and insert macID : 2, but it does not insert macID : 2 but it updates macID : 1.

推荐答案

{"macID" : {$in : [1,2]}} 并不表示你正在搜索一个两个文件(使用 "macID" : 1"macID" : 2),这意味着您正在搜索 macID 等于 12.

{"macID" : {$in : [1,2]}} do not means that you are searching a two documents (with "macID" : 1 and "macID" : 2), it means that you are searching any documents which have macID eaqual to 1 or 2.

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

So upsert: true tells to MongoDB to create only one document (not two).

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

You must provide the multiple update requests (use bulkWrite with updateOne not updateMany).

这篇关于mongoDB updateMany with upsert true 和 $in in where 条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆