【问题标题】:ARRAY FILTERS in mongooDBMongoDB 中的数组过滤器
【发布时间】:2020-09-21 11:40:51
【问题描述】:

我有以下架构

{
        "_id" : ObjectId("5ec0471dfec11a07d80c9d07"),
        "name" : "jasper",
        "post" : [
                {
                        "_id" : ObjectId("5ec0473ffec11a07d80c9d08"),
                        "content" : "It,s all about........",
                        "title" : "THE NEEDY"
                },
                {
                        "_id" : ObjectId("5ec0475afec11a07d80c9d09"),
                        "content" : "I know..........",
                        "title" : "The world"
                }
        ],
        "__v" : 2
}

我想更新特定帖子中的内容部分。我正在使用猫鼬。 我尝试了以下查询。虽然它没有显示任何错误,但它没有在数据库中的数据中更新。

var id="5ec0471dfec11a07d80c9d07";
 var subid="5ec0473ffec11a07d80c9d08";
data.updateOne(
    {'_id.post._id':subid},
    {
      $set:{
        "$[post].post.$[rely].content":'ohkkk'
      }
    },
    {arrayFilters:[{"post._id":id},{"rely._id":subid}],new:true}
  );

你能帮我找出错误吗?

【问题讨论】:

  • 有一个文档匹配{'_id.post._id':subid},所以不会有upsert,但是post数组中没有匹配{"post._id":id}的元素,所以什么都没有修改
  • 你试过我提供的解决方案了吗?您的问题还需要帮助吗?
  • 我试过了,但它仍然没有更新数据。 Mongoshell 中的输出是 { "acknowledged" : true, "matchedCount" : 0, "modifiedCount" : 0 } 而 post(ieres.send('post')) 的输出是 {"ok":0," n":0,"nModified":0} 在快递应用程序中。@JakubASuplicki

标签: arrays mongodb mongoose


【解决方案1】:

如果您想使用arrayFilters,请尝试以下代码:

data.updateOne({_id: id},
        { 
            "$set": {[`post.$[inner].content`]: 'ohkkk'} 
        },
        { 
            "arrayFilters": [{ "inner._id": subid }],
            new: true
        },
        function(err, post) {
            if (!err) {
                res.send(post)
            }
        })

或者,由于它是 1 级嵌套数组,您可以这样做:

data.updateOne({ _id: id, "post._id": subid }, { $set: { "post.$.content": 'ohkkk' }, { new: true } })

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-06
    • 2018-08-19
    • 2019-11-05
    • 2021-09-29
    相关资源
    最近更新 更多