2

I would like to upsert an element in an array, based on doc _id and element _id. Currently it works only if the element is allready in the array (update works, insert not).

So, these collection:

[{
        "_id": "5a65fcf363e2a32531ed9f9b",
        "ressources": [
            {
                "_id": "5a65fd0363e2a32531ed9f9c"
            }
        ]
    }]

Receiving this request:

query = { _id: '5a65fcf363e2a32531ed9f9b', 'ressources._id': '5a65fd0363e2a32531ed9f9c' };
update = { '$set': { 'ressources.$': { '_id': '5a65fd0363e2a32531ed9f9c', qt: '153', unit: 'kg' } } };
options = {upsert:true};
collection.update(query,update,options);

Will give this ok result:

[{
        "_id": "5a65fcf363e2a32531ed9f9b",
        "ressources": [
            {
                "_id": "5a65fd0363e2a32531ed9f9c",
                "qt": 153,
                "unit": "kg"
            }
        ]
    }]

How to make the same request work with these initial collections:

    [{
        "_id": "5a65fcf363e2a32531ed9f9b"
    }]

OR

[{
        "_id": "5a65fcf363e2a32531ed9f9b",
        "ressources": []
    }]

How to make the upsert work? Does upsert works with entire document only? Currently, I face this error:

The positional operator did not find the match needed from the query.

Thanks

Slim
  • 1,256
  • 1
  • 13
  • 25
  • It is not possible. Workarounds [here](https://stackoverflow.com/questions/13588342/can-mongo-upsert-array-data) – s7vr Jan 23 '18 at 17:42

1 Answers1

1

I also tried to figure out how to do it. I found only one way:

  1. fetch model by id
  2. update array manually (via javascript)
  3. save the model

Sad to know that in 2018 you still have to do the stuff like it.

UPDATE:

This will update particular element in viewData array

db.collection.update({
    "_id": args._id, 
    "viewData._id": widgetId
}, 
{
    $set: {
        "viewData.$.widgetData": widgetDoc.widgetData
    } 
})

$push command will add new items

Alexey Sh.
  • 1,734
  • 2
  • 22
  • 34