Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB add values to array if not exists

I have this collection :

{
username : "user1",
arr : [
    {
        name : "test1",
        times : 0
    },
    {
        name : "test2",
        times : 5
    }
]
}

I have an array with some object. This objects have a name and the value times. Now I want to add new objects, if my array doesn't contain them. Example:

I have this two objects with the name "test1" and "test2" already in the collection. I want now to insert the objects "test2", "test3" and "test4". It should only add the object "test3" and "test4" to the array and not "test2" again. The value times doesn't do anything in this case, they should just have the value 0 when it gets insert.

Is there a way to do this with one query?

like image 897
user6586661 Avatar asked Feb 08 '17 14:02

user6586661


People also ask

How do I add values to an array in MongoDB?

In MongoDB, you can use the $push operator to append a value to an array. This operator can be used with various modifiers, one of which is the $position modifier. The $position modifier allows you to specify the position within the array that you want to insert the new value.

How do you update an array element 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 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. questions array if the associated grades.

What is $addToSet?

$addToSet returns an array of all unique values that results from applying an expression to each document in a group. The order of the elements in the returned array is unspecified. $addToSet is available in these stages: $bucket.


1 Answers

If you can insert test1, test2,... one by one, then you can do something like this.

db.collection.update(
{username : "user1", 'arr.name': {$ne: 'test2'}}, 
{$push: {
     arr: {'name': 'test2', 'times': 0}
   }
})

The $ne condition will prevent the update if the name is already present in arr.

like image 149
Tarush Arora Avatar answered Nov 07 '22 11:11

Tarush Arora