Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB Update array element (document with a key) if exists, else push

I have such a schema:

doc:
{
    //Some fields
    visits:
    [
        {
            userID: Int32
            time: Int64
        }
    ]

}

I want to first check if a specific userID exists, if not, push a document with that userID and system time, else just update time value. I know neither $push nor $addToSet are not able to do that. Also using $ with upsert:true doesn't work, because of official documentation advice which says DB will use $ as field name instead of operator when trying to upsert.

Please guide me about this. Thanks

like image 612
Alireza Mohamadi Avatar asked Dec 24 '16 18:12

Alireza Mohamadi


People also ask

How do you update an element in an array in MongoDB?

You can use the updateOne() or updateMany() methods to add, update, or remove array elements based on the specified criteria. It is recommended to use the updateMany() method to update multiple arrays in a collection.

How do I push an array into an array in MongoDB?

In MongoDB, the $push operator is used to appends a specified value to an array. If the mentioned field is absent in the document to update, the $push operator add it as a new field and includes mentioned value as its element. If the updating field is not an array type field the operation failed.

How do I update a nested array in MongoDB?

Update Nested Arrays in Conjunction with $[]The $[<identifier>] filtered positional operator, in conjunction with the $[] all positional operator, can be used to update nested arrays. The following updates the values that are greater than or equal to 8 in the nested grades.


1 Answers

You can use $addToSet to add an item to the array and $set to update an existing item in this array.

The following will add a new item to the array if the userID is not found in the array :

db.doc.update({
    visits: {
        "$not": {
            "$elemMatch": {
                "userID": 4
            }
        }
    }
}, {
    $addToSet: {
        visits: {
            "userID": 4,
            "time": 1482607614
        }
    }
}, { multi: true });

The following will update the subdocument array item if it matches the userId :

db.doc.update({ "visits.userID": 2 }, {
    $set: {
        "visits.$.time": 1482607614
    }
}, { multi: true });
like image 149
Bertrand Martel Avatar answered Oct 18 '22 20:10

Bertrand Martel