首页 文章

如何从Mongodb数组文档中删除项目

提问于
浏览
0

我有以下mongodb集合名为Posts,文档如下:

{
    "_id" : "111",
    "comments" : [
        {
            "replyPost" : "aaaa",
            "username" : "John Doe"
        },
        {
            "replyPost" : "bbbb",
            "username" : "Jane Smith"
        },
        {
            "replyPost" : "cccc",
            "username" : "Jane Smith"
        },
        {
            "replyPost" : "dddd",
            "username" : "Jane Smith"
        }
    ]
}

我试图用replyPost:“cccc”删除一个数组项,所以结果将是:

{
    "_id" : "111",
    "comments" : [
        {
            "replyPost" : "aaaa",
            "username" : "John Doe"
        },
        {
            "replyPost" : "bbbb",
            "username" : "Jane Smith"
        },
        {
            "replyPost" : "dddd",
            "username" : "Jane Smith"
        }
    ]
}

我用$ pull参考mongodb文件https://docs.mongodb.com/manual/reference/operator/update/pull/试过.update方法

Posts.update(
  {_id: this._id},
  { $pull: { comments: { replyPost:"cccc"} } }
);

似乎没有工作 . 有谁能看到这个问题?

3 回答

  • 0

    看看你是否得到了正确的_id . 它是字符串格式 .

    我在mongo shell中试过了同样的东西 . 它对我有用 .

    这是日志:

    > db.posts.insert({
    ...     "_id" : "111",
    ...     "comments" : [
    ...         {
    ...             "replyPost" : "aaaa",
    ...             "username" : "John Doe"
    ...         },
    ...         {
    ...             "replyPost" : "bbbb",
    ...             "username" : "Jane Smith"
    ...         },
    ...         {
    ...             "replyPost" : "cccc",
    ...             "username" : "Jane Smith"
    ...         },
    ...         {
    ...             "replyPost" : "dddd",
    ...             "username" : "Jane Smith"
    ...         }
    ...     ]
    ... })
    WriteResult({ "nInserted" : 1 })
    > db.posts.update({_id:'111'},{$pull:{comments:{replyPost:'cccc'}}})
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
    > db.posts.findOne()
    {
            "_id" : "111",
            "comments" : [
                    {
                            "replyPost" : "aaaa",
                            "username" : "John Doe"
                    },
                    {
                            "replyPost" : "bbbb",
                            "username" : "Jane Smith"
                    },
                    {
                            "replyPost" : "dddd",
                            "username" : "Jane Smith"
                    }
            ]
    }
    
  • 0

    如果你使用的是猫鼬,你可以这样做:

    db.posts.remove({replyPost: 'cccc'}, function(err) {
    })
    

    第一个参数可以是任何mongoose查询表达式 . 所有匹配项都将从db中删除 .

    mongoose remove

  • 0

    经过测试的作品:

    Posts.update((
      {"_id" : "111"},
      { $pull: {comments: {"replyPost" : "cccc"}} },
      { multi: true }
    )
    

相关问题