MongoDB
 sql >> Datenbank >  >> NoSQL >> MongoDB

Aktualisieren Sie das Array in Mongo und upsert

Es gibt eine Option, um zu erreichen, was Sie wollen.

// step 1
var writeResult = db.collection.update({
    "providerId" : ID,
    "providers" : {
        $elemMatch : {
            "merchantId" : MERCHANTID
        }
    }
}, {
    $set : {
        "providers.$.merchantId" : MERCHANTID,
        "providers.$.name" : NAME,
        "providers.$.valid" : true,
        "providers.$.data" : DATA
    }
});


// step 2
if (!writeResult.nModified) { // if step 1 has succeeded on update, nModified == 1, else nModified == 0
    db.collection.update({
        "providerId" : ID,
        "providers.merchantId" : {
            $ne : MERCHANTID        // this criteria is necessary to avoid concurrent issue
        }
    }, {
        "$push" : {
            "prividers" : {
                "merchantId" : MERCHANTID,
                "name" : NAME,
                "valid" : true,
                "data" : DATA
            }
        }
    });
}