Update array in mongo and upsert

不想你离开。 提交于 2019-12-23 02:18:10

问题


I'm trying to update an array within a document and it works correctly, but when I want to add a new element with upsert fails how to run an error. I've been searching on google for a few hours and the mongodb documentation and what I have tried I cannot operate.

The structure of the collection is:

{
"name" : String,
"providerId": Number,
"description": String,
"providers": [
    {
        "merchantId": String,
        "name": String,
        "valid": Boolean,
        "data": String
    },
    {
        "merchantId": String,
        "name": String,
        "valid": Boolean,
        "data": String
    },
    {
        "merchantId": String,
        "name": String,
        "valid": Boolean,
        "data": String
    }
]
}

Use this query to update existing data:

db.collection.update( { "providerId": ID, "providers": { $elemMatch: { "merchantId": MERCHANTID }}}, { $set: {

    "providers.$.merchantId": MERCHANTID,
    "providers.$.name": NAME,
    "providers.$.valid": true,
    "providers.$.data": DATA

}});

This working properly and correctly updated me the elements of the array. I want to when an element does not exist add it, without knowing if there are items or not, but not is if possible, probe to add upsert ( { upsert: true } ) parameter but gives me the following error. I think it is because it does not return any object search.

This is the error:

MongoError: The positional operator did not find the match needed from the query. Unexpanded update: providers.$.name

Is there any way to update the data in the subdocuments in the array and is compatible with add new ones if they don't exist? I've tried to search with the operator $in and it gives me error; also probe to search in different ways ( { "providers.merchantId": MERCHANTID } ) and others.

Thanks


回答1:


There is an option to achieve what you want.

// 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
            }
        }
    });
}


来源:https://stackoverflow.com/questions/26320673/update-array-in-mongo-and-upsert

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!