首页 > 解决方案 > 在 mongoDB 上增加匹配特定要求的子文档

问题描述

语境

问题

我想使用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**,
    }]
}

任何的想法 ?

标签: mongodbmongoose

解决方案


我认为你应该尝试这样的事情:

MyModel.findOneAndUpdate({
    _id: docId, 
    'subdocuments.position': { $gte: 2},
  }, { 
    $inc : {'subdocuments.$.position': 1}
  });

推荐阅读