heterogeneous bulk update in mongodb

前端 未结 3 1935
甜味超标
甜味超标 2021-02-14 22:58

I know that we can bulk update documents in mongodb with

db.collection.update( criteria, objNew, upsert, multi )

in one db call, but it\'s homo

3条回答
  •  你的背包
    2021-02-14 23:18

    That's two seperate questions. To the first one; there is no MongoDB native mechanism to bulk send criteria/update pairs although technically doing that in a loop yourself is bound to be about as efficient as any native bulk support.

    Checking for the existence of a document based on an embedded document (what you refer to as compound key, but in the interest of correct terminology to avoid confusion it's better to use the mongo name in this case) and insert/update depending on that existence check can be done with upsert :

    document A :

    {
        _id: ObjectId(...),
        key: {
            name: "Will",
            age: 20
        }
    }
    
    db.users.update({name:"Will", age:20}, {$set:{age: 21}}), true, false)
    

    This upsert (update with insert if no document matches the criteria) will do one of two things depending on the existence of document A :

    • Exists : Performs update "$set:{age:21}" on the existing document
    • Doesn't exist : Create a new document with fields "name" and field "age" with values "Will" and "20" respectively (basically the criteria are copied into the new doc) and then the update is applied ($set:{age:21}). End result is a document with "name"="Will" and "age"=21.

    Hope that helps

提交回复
热议问题