Home > Blockchain >  Creating a field in an a object if it doesn't exist, incrementing it if it does if it does, for
Creating a field in an a object if it doesn't exist, incrementing it if it does if it does, for

Time:11-20

I have a collection "users"

{
  "id": "u101",
  "notifications": {}
},


{
  "id": "u102",
  "notifications": {"channelId": 1}
},

There's a notifications field that has an object. Every field of this object corresponds to a chat channel ID and they value is the amount of notifications in the channel (unread messages).

If user "u101" and "u102" are both in the the same channel and they recieve a notification, I'd need to create a "channelId" field for user "u101" and set the value to 1. I'd also need to update the value for user "u102" and set the value of "channelId" to 2

The expected result is as follows:

{
  "id": "u101",
  "notifications": {"channelId": 1}
},


{
  "id": "u102",
  "notifications": {"channelId": 2}
},

I have tried doing it by simply querying the "users" collection, getting the array with the users back and then looping over it with ES6 functions like this:

users.forEach(user => {
            user.notifications.hasOwnProperty(channelId) ?
                user.notifications[channelId]  
                :
                user.notifications[channelId] = 1
        })

It works well but the problem is that I need to update all the users one by one in a loop with

collection.updateOne({ '_id': user._id }, { $set: user })

And it can amount to a LOT of users in one channel. Is there a way to this with one MongoDB command?

CodePudding user response:

You can use $inc in order to increment or create the value (if not exists) to all wanted documents in a single query:

db.collection.update(
  {},
  {$inc: {"notifications.channelId": 1}},
  {multi: true}
)

See how it works on the playground example

  • Related