node.jsmongodbmongodb-queryaggregation-frameworkmongo-collection

Update MongoDB field value only if new providerId not exists


I have the following document in MongoDB.

{
    "_id" : ObjectId("5ce34ac6a2f25b2448b9b3a3"),
    "userId" : ObjectId("5ce34ac6a2f25b2448b9b3a0"),
    "providers" : [ 
        "1689736266", 
        "1598763690", 
        "1528069614", 
        "1831364272", 
        "1548463045", 
        "1245301159", 
        "1386616399", 
        "1790775971", 
        "1629462130", 
        "1992169783"
    ],
    "countByType" : {
        "doctors" : 6,
        "labs" : 0,
        "hospitals" : 0,
        "imagingCenters" : 0,
        "other" : 4
    }
}

I am not sure on how to check for a new providerId in providers array and update if not exists with a single query operation. So first I need to check for a particular providerId exists or not, if not exists then update the providers field else ignore it.

How can I implement this?


Solution

  • I think what you need is the $addToSet operator. You can add multiple values without worrying about appending duplicates like so:

    db.test.update(
     {userId : ObjectId("5ce34ac6a2f25b2448b9b3a0")},
     {$addToSet  : {providers : { $each:["1","1689736266", "23"]} }}
    )