Watch keynotes and sessions from MongoDB.live, our virtual developer conference.

An updateMany with $addToSet returns varying modifiedCount results

Hello. I have a collection called ‘locations’ and it has 64 documents, each has a field called ‘subscribers’ and the value is an array of email addresses. When I tried to run db.collection('locations') .updateMany({},{ $pull: {subscribers: 'some@email.com'} }); and db.collection('locations') .updateMany({},{ $addToSet: {subscribers: 'some@email.com'} }); again and again, the modifiedCount should always be 64, right? But it returns a random number every time and loses data. The matchedCount is always 64, no error. Why does that happen? It’s weird because when I try these updates on a test db and collection, it doesn’t happen, but on my production db and collection, it happens. Is it because I have too frequent queries that locks the documents? But mongodb has journal that can help recover from heavy load, doesn’t it? I am so confused. Please help!

I am running on an M2 cluster and there are a couple of connections querying and updating the cluster. I use the Node.js driver.

Hello Shaotian_Dong,

$pull removes all instances of the email address values from the array; i.e., if there are duplicate values of the email address, all the matching values are removed. $addToSet only adds an email if it doesn’t exist in the array. $push adds an email even if the email already exists in the array.

Also, you may be using different set of data in your test db (as you are getting different results).

I suggest check your data before and after updating the documents / array. Since, you are using NodeJS driver, you can post the code you are running.

1 Like