laravel 如何在mongo collection中仅在子数组小于50的情况下向特定文档的子数组中添加新项

pqwbnv8z  于 2022-11-26  发布在  Go
关注(0)|答案(1)|浏览(80)

我在mongoDB中有一个用户集合,现在我只想在favorites数组的大小小于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.
yeotifhr

yeotifhr1#

也许是这样的:

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

解释道:
1.查找要更新的文档by _id,其中收藏夹[50]元素不存在
(数组元素50将不存在于具有〈50个收藏夹的所有文档中)
1.$将新对象推入文档
Playground

相关问题