ng.newbie
ng.newbie

Reputation: 3218

MongoDB query for adding to array if not present

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 ?

Upvotes: 1

Views: 46

Answers (1)

Dheemanth Bhat
Dheemanth Bhat

Reputation: 4452

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"
        }
    }
});

Upvotes: 1

Related Questions