1

Desired Behavior:

Delete a property from each object in an array of objects in all documents in a collection.

What I've Tried:

The docs show $unset is used for deleting object properties:

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

Another post gives an example of how to delete a nested property in multiple documents:

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

Source: https://stackoverflow.com/a/31384375

I had a look at:

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

which gave the example:

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

So I tried the following and it seems to work:

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

Question:

Is this the correct way to:

delete each weight property in each object in array_of_objects in all documents

Schema:

{
    "_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"
    }]
}
3

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.