如何从集合中所有文档的对象数组中的每个对象删除属性?

时间:2019-07-04 12:56:44

标签: node.js mongodb

所需行为:

从集合中所有文档的对象数组中的每个对象删除属性。

我尝试过的事情:

文档显示$unset用于删除对象属性:

db.products.update(
   { sku: "unknown" },
   { $unset: { quantity: "", instock: "" } }
)

另一篇文章给出了如何删除多个文档中的嵌套属性的示例:

db.collectionName.update(
    { },
    { "$unset": { "values.727920": "" } },
    { "multi":true }
)

来源:https://stackoverflow.com/a/31384375

我看过:

https://docs.mongodb.com/manual/reference/operator/update/positional-all/
https://docs.mongodb.com/manual/reference/operator/update/positional-all/#positional-update-all

给出了示例:

db.students.update(
   { },
   { $inc: { "grades.$[]": 10 } },
   { multi: true }
)

所以我尝试了以下操作,并且似乎正常工作:

db.my_collection.update(
    { },
    { "$unset" : { "array_of_objects.$[].weight": "" } },
    { "multi" : true }
)

问题:

这是正确的方法吗?

  

删除weight中每个对象中的每个array_of_objects属性   所有文件

架构:

{
    "_id": ObjectId("5d1d85aa00341124bc90d158"),
    "title": "hello 01",
    "array_of_objects": [
    {
        "color": "blue",
        "weight": "100",
        "date": "2019-07-04T11:12:59.356Z"
    },
    {
        "color": "blue",
        "weight": "100",
        "date": "2019-07-04T11:12:59.356Z"
    },
    {
        "color": "blue",
        "weight": "100",
        "date": "2019-07-04T11:12:59.356Z"
    }]
},
{
    "_id": ObjectId("5d1d85aa11341124bc90d158"),
    "title": "hello 02",
    "array_of_objects": [
    {
        "color": "blue",
        "weight": "100",
        "date": "2019-07-04T11:12:59.356Z"
    },
    {
        "color": "blue",
        "weight": "100",
        "date": "2019-07-04T11:12:59.356Z"
    },
    {
        "color": "blue",
        "weight": "100",
        "date": "2019-07-04T11:12:59.356Z"
    }]
},
{
    "_id": ObjectId("5d1d85aa22341124bc90d158"),
    "title": "hello 03",
    "array_of_objects": [
    {
        "color": "blue",
        "weight": "100",
        "date": "2019-07-04T11:12:59.356Z"
    },
    {
        "color": "blue",
        "weight": "100",
        "date": "2019-07-04T11:12:59.356Z"
    },
    {
        "color": "blue",
        "weight": "100",
        "date": "2019-07-04T11:12:59.356Z"
    }]
}

0 个答案:

没有答案