Search code examples
mongodbpushupdating

MongoDB push item only if it does not exist


I have a document with the following fields:

{
    "id" : 15,
    "existingCodes" : [ 
        {
            "_id" : ObjectId("5c49a6c03a95f50b15409296"),
            "code" : "first"
        }, 
        {
            "_id" : ObjectId("5c49a6c03a95f50b15409295"),
            "code" : "second"
        }, 
        {
            "_id" : ObjectId("5c49a6c03a95f50b15409294"),
            "code" : "third"
        }, 
        {
            "_id" : ObjectId("5c49a6c03a95f50b15409293"),
            "code" : "fourth"
        }
    ]
}

The problem is that I'm trying to push a new object to the existingCodes array but making sure that the code value does not already exist, and every solution that I've tried is not working.

I've tried to achieve this using $push and $ne, but it adds duplicate field:

db.getCollection('codes').update({ id: 15, 'existingCodes.code': { $ne: 'first' } }, { $push: { existingCodes: { code: 'first' } } })

But it doesn't add the duplicate field if I change $ne to match "second" or any other existing code value different than "first", and I don't understand why.

I've also tried to use $addToSet:

db.getCollection('codes').update({ id: 15, }, { $addToSet: { existingCodes: { code: 'first' } } })

Solution

  • Add to set works fine you are using id in the match condition in place of _id attaching a screenshot as well! addToset.PNG