0

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
Vishnu
  • 704
  • 12
  • 34
  • "if not exists then update the providers field else ignore it." - could you clarify that part ? Do you want to push the value if it does not exist or you want to do something else ? – mickl May 24 '19 at 13:55
  • 1
    @mickl Yes I want to push the provider id into array if value does not exist, so that it gets added to end of existing array.... – Vishnu May 24 '19 at 13:59

2 Answers2

1

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"]} }}
)
Bajal
  • 5,487
  • 3
  • 20
  • 25
  • One doubt I already used the following query for updating provider and count: let updateProviderId = await userProviderCollection.update( regUserId, { $set: { providers: providernpiId, countByType: providercountType } }); where providernpiId is full array, not single element. So if i used {$addToSet : {providers : { $each:["1","1689736266", "23"]} }} will this overwrite the existing array? – Vishnu May 24 '19 at 14:15
  • It won't. It just appends to existing array – Bajal May 24 '19 at 15:59
1

As per documentation "The $addToSet operator adds a value to an array unless the value is already present, in which case $addToSet does nothing to that array.". Also will it be the case when you would be trying to add multiple values same time in providers array?. If yer then use $each else you would not need $each.

Garry
  • 536
  • 1
  • 5
  • 11
  • i already have some values in array which i updated as whole array.. in this scenario i have some array values which i need to check if exists in array, not single value but as a single array. So in this case which one should i choose.. – Vishnu May 24 '19 at 15:00
  • In that case you should use $addToSet and $each option. Same as answered by @bajal. So $each will check each value in the new array and $addToSet check if that value exists in providers, if not insert it else not do anything. – Garry May 24 '19 at 15:20