从 MongodDB 中的数组中删除子文档 [英] Removing a subdocument from array in MongodDB

查看:44
本文介绍了从 MongodDB 中的数组中删除子文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 node 和 mongodb,但在从我似乎无法弄清楚的集合中的数组中删除子文档时遇到了问题.

I'm working with node and mongodb and having an issue removing a subdocument from an array in my collection that I can't seem to figure out.

来自我的cardHolders"集合的示例文档看起来像(为简洁起见,去掉了其他字段):

A sample document from my 'cardHolders' collection looks like(stripped of other fields for brevity):

{
    "_id" : ObjectId("51ee899ec15d5aaff39d3352"),
    "cards" : [
            {
               "rfid_id" : ObjectId("51ee899ec15d5aaff39d335a")
            }
    ]
}

我试图做的是找到所有 cardHolder 文档,这些文档在卡数组中具有带有 rfid_id 值的子文档.

What I'm attempting to do is find all cardHolder documents that have a subdocument with a rfid_id value in the cards array.

我试过 mongo 命令:

I've tried the mongo command:

db.cardholders.update({}, 
    {$pull:{ "cards": {"rfid_id": ObjectId("51ee899ec15d5aaff39d335a")}}},
    false, false)

虽然我没有收到任何语法错误,但我的收藏中没有任何文件受到影响 - 对此问题的任何帮助将不胜感激!

And while I don't get any syntax errors, no documents in my collection are effected - Any assistance on this matter would be greatly appreciated!

使用完整的文档详细信息进行

Edit with full document details:

{
    "_id" : ObjectId("51ee899ec15d5aaff39d3353"),
    "first" : "first",
    "last" : "last",
    "email" : "email",
    "phone" : "555 555 5555",
    "userRole" : "su",
    "cards" : [
            {
                    "rfid_id" : ObjectId("51ee899ec15d5aaff39d3359")
            }
    ],
    "zones" : [
            {
                    "zone_id" : ObjectId("51ee899ec15d5aaff39d3357")
            }
    ]
}

推荐答案

您的示例工作正常:

db.so.drop();
db.so.insert(
{
    "_id" : ObjectId("51ee899ec15d5aaff39d3353"),
    "first" : "first",
    "last" : "last",
    "email" : "email",
    "phone" : "555 555 5555",
    "userRole" : "su",
    "cards" : [
            {
                    "rfid_id" : ObjectId("51ee899ec15d5aaff39d3359")
            }
    ],
    "zones" : [
            {
                    "zone_id" : ObjectId("51ee899ec15d5aaff39d3357")
            }
    ]
});

db.so.update({}, {$pull:{ "cards": {"rfid_id": ObjectId("51ee899ec15d5aaff39d3359")}}}, false, false)
db.so.find().pretty();

输出:

{
    "_id" : ObjectId("51ee899ec15d5aaff39d3353"),
    "cards" : [ ],
    "email" : "email",
    "first" : "first",
    "last" : "last",
    "phone" : "555 555 5555",
    "userRole" : "su",
    "zones" : [
        {
            "zone_id" : ObjectId("51ee899ec15d5aaff39d3357")
        }
    ]
}

虽然我确实需要稍微更改拉取的 ObjectID,因为它最初在文档的简单版本和完整版本之间使用不同的字符串.

Although I did have to change the ObjectID for the pull slightly, as it was originally using a different string between your simple and full versions of the document.

这篇关于从 MongodDB 中的数组中删除子文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆