9

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?

2
  • Will those objects you are adding have the times key as well? Commented Feb 8, 2017 at 14:58
  • @chridam yes, but they have just the "times : 0". Commented Feb 8, 2017 at 15:01

2 Answers 2

19

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, that will work. And a little other question. Can I update something else, if $ne prevents to insert my object?
@user6586661 Yes, you can specify in update parameter of the query, whatever you want to update.
4

You can now use the addToSet operator that is built just for that: adds a value to an array if it does not exist.

Documentation: https://docs.mongodb.com/manual/reference/operator/update/addToSet/

1 Comment

But that does not guarantee to preserve the order, unfortunately, so it's not equivalent.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.