1

I am new to MongoDB and want to know if there is any way to add an embedded document to an array if it is not present.

Let's say I have a collection called products:

{
    _id: "123",
    name: "Hair-Dryer",
    locations: [{
            code: "MA",
            name: "Massachusetts"
        },
        {
            code: "IL",
            name: "illinois"
        }
    ]
}, {
    _id: "456",
    name: "Toaster",
    locations: [{
        code: "MA",
        name: "Massachusetts"
    }, ]
}

Now lets say I want to add :

{
        code: "IL",
        name: "illinois"
}

To only those documents which don't have them. Note that, I don't know which documents have my required data or which don't have them. I need to find that out.

How can I write a query like this in MongoDB ?

1 Answer 1

1

The $addToSet operator adds a value to an array unless the value is already present, in which case $addToSet does nothing to that array.

Try this:

db.locations.updateMany({}, {
    $addToSet: {
        locations: {
            code: "IL",
            name: "illinois"
        }
    }
});
Sign up to request clarification or add additional context in comments.

Comments

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.