在mongodb中添加和删除嵌套对象中的多个字段

时间:2016-04-05 14:00:41

标签: mongodb object nested

我有这样插入的MongoDB数据:

db.orders.insert({ _id: ObjectId().str, name: "admin", status: "online",catalog : [
    {
        "objectid" : ObjectId().str,
        "message" : "sold",
        "status" : "open"
    }
]})

首先,我想在目录对象中添加新字段,我这样做:

db.orders.update({"_id":"5703b86df3d607cb5fa75ff3"},{$set: {"catalog.0.day": "tuesday"},{"catalog.0.payments": "paypal"}});

该代码因此错误而失败:

2016-04-05T16:48:41.757+0300 E QUERY    [thread1] SyntaxError: invalid property id @(shell):1:88

我还想删除一些字段,我准备使用以下代码:

db.orders.update({"_id":"5703b86df3d607cb5fa75ff3"},{$unset: {"catalog.0.day": ""},{"catalog.0.payments": ""}});

为什么更新语句失败,如何删除我添加的字段?

1 个答案:

答案 0 :(得分:2)

将此用于$set

db.orders.update(
    {"_id":"5703b86df3d607cb5fa75ff3"},
    {$set: {
            "catalog.0.day": "tuesday",
            "catalog.0.payments": "paypal"
        }
    });

这是$unset

db.orders.update(
    {"_id":"5703b86df3d607cb5fa75ff3"},
    {
        $unset: {
            "catalog.0.day": "",
            "catalog.0.payments": ""
        }
    });

如果您只想使用一次更新通话,则可以执行以下操作:

db.orders.update(
    {"_id":"5703b86df3d607cb5fa75ff3"},
    {
        $unset: {
            "catalog.0.day": "",
            "catalog.0.payments": ""
        },
        $set: {
            "catalog.0.day": "tuesday",
            "catalog.0.payments": "paypal"
        }
    });

如果您想要多条记录,那么:

db.orders.update(
    {"status":"online"},
    {
        $unset: {
            "catalog.0.day": "",
            "catalog.0.payments": ""
        },
        $set: {
            "catalog.0.day": "tuesday",
            "catalog.0.payments": "paypal"
        }
    },
    {
        multi: true
    });

请注意,在此版本中,我的查询文档已更改为更常规的字段。而不是_id