mongodb - 在 mongoDB 上增加匹配特定要求的子文档
问题描述
语境
- MongoDB 4.0
- 猫鼬 ODM 5.4.15
问题
我想使用update
函数增加与特定给定要求匹配的嵌套子文档。
这是我将更新的原始示例文档:
{
_id: 5c73fba86cd17000576eef83,
subdocuments :[{
_id: 5c73fba86cd17000576eef84,
position: 3,
}, {
_id: 5c73fba86cd17000576eef85,
position: 0,
}, {
_id: 5c73fba86cd17000576eef86,
position: 2,
}, {
_id: 5c73fba86cd17000576eef87,
position: 1,
}, {
_id: 5c73fba86cd17000576eef88,
position: 4,
}]
}
我想将位置超过2$inc
的元素放入subdocuments
数组中。$gte
更新后,给定的文档应变为:
{
_id: 5c73fba86cd17000576eef83,
subdocuments :[{
_id: 5c73fba86cd17000576eef84,
position: **4**,
}, {
_id: 5c73fba86cd17000576eef85,
position: 0,
}, {
_id: 5c73fba86cd17000576eef86,
position: **3**,
}, {
_id: 5c73fba86cd17000576eef87,
position: 1,
}, {
_id: 5c73fba86cd17000576eef88,
position: **5**,
}]
}
任何的想法 ?
解决方案
我认为你应该尝试这样的事情:
MyModel.findOneAndUpdate({
_id: docId,
'subdocuments.position': { $gte: 2},
}, {
$inc : {'subdocuments.$.position': 1}
});
推荐阅读
- google-sheets - 使用具有实时刷新功能的 API 连接表格
- angular-cli - 将路由器添加到 Angular 9 项目
- reactjs - ReactJS - 将部分 onClick 函数作为来自父组件的道具传递
- c# - 电阻两端电压
- python - 为什么将日期时间功能设置为默认时不需要迁移?
- c++ - 如何在 2 个数组之间打印不常见的值?
- spring-boot - 使用 Minikube 在本地 dev 上一起运行多个微服务 docker 映像
- java - 如何在不使用 Toast 的情况下向播放器屏幕显示总分
- build - yocto 内核模块配方
- python - ipv4 正则表达式代码在一个元组中给出输出,每个八位字节作为元组中的元素。如何直接打印ip地址?