How should I update multiple documents based on an array input of _id's?

Hi, I’m trying to set up a Notifications system. I have a Notifications collection which contains the following data:

   "_id": "newNotificationID",
   "userID": "someUserID",
   "type": "typeOfNotification"

For each User, they may have a number of followers, and I have stored the follower’s userIDs in an array as a field of the User’s document:

   "_id": "someUserID",
   "followers": ["followerA_ID", "followerB_ID", ... ],
   "notifications": ["notification1_ID", ... ]

How should I be bulk updating all the documents matching the respective follower ID’s, and pushing the newNotificationID to this Notifications array? When a new Notification is generated by a user, I need to update that user’s entire followers list.

Can this only be done in a loop, by iterating over each follower, or is there a faster way to update multiple documents at the same time? So when someUserID does an action and I generate a newNotificationID, I need to push newNotificationID to ALL of somerUserID’s follower’s User documents. So I need to push it to followerA_ID's notifications array, followerB_ID's notifications array, so on and so forth.

I’m not sure if this is a good design in the first place, but if I need to do it this way how should I be going about it?

Hello @Ajay_Pillay,

You can use the bulkWrite as shown below (the syntax is for the mongo shell):

let newNotificationID = "some value";
let followers_arr = db.users.findOne( { _id: "someUserID" }, { _id: 0, followers: 1 } ).followers;
let bulk_ops_arr = [];

for (let follower of followers_arr) {
    let update_op = { updateOne : { "filter" : { "_id" : follower }, "update" : { $push : { "notifications" : newNotificationID } } } };


When you run the db.users.bulkWrite(..., the updates are sent to the database server as a single call, where all the uodates are performed on the server and you get the update result. It is, in general, an efficient operation than sending an individual update for each of the follower.

The bulkWritereturns a result which has information about all the updated documents, total documents updated, etc.

I’m not sure if this is a good design in the first place…

I cannot tell if its an efficient design. The data design (or model) should meet the application needs well - in terms of functionality, coding, performance, etc.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.