0

I have a users collection in my mongoDB. Now I want to update favorites array only if its size is less than 50.

  "_id": 'mongo_id',
  "name": "test user",
  "email": "test_4@gmail.com",
  "full_name": "",
  "first_name": "",
  "last_name": "",
  "mobile_number": "",
  "email_id": "test_4@gmail.com",
  "profile_photo": "",
  "roles": [],
  "favorites": [
    { obj1 }, { obj2 }, { obj3 }, { obj4 }, 
  ],
}```

Currently I'm doing it crude way.
Getting all the favorites and checking the size and then pushing the new object into it.

Is there any better approach using mongodb query operators ?

I want to check the size < 50 and then update array in single db call.
kakurala
  • 824
  • 6
  • 15

1 Answers1

0

Maybe something like this:

db.collection.update({
  _id: "mongo_id",
  "favorites.50": {
   "$exists": false
}
},
{
"$push": {
favorites: {
  obj: 10
  }
}
})

Explained:

  1. Find document to update by _id where favorites[50] element do not exists

( array element 50 will not exists for all documents with < 50 favorites )

  1. $push the new object in the document

Playground

R2D2
  • 9,410
  • 2
  • 12
  • 28