skip to Main Content

I have one entry in my Data collection and is as follows:

{
    "data": [
        {
            "key1": {
                "name": "test"
            }
        },
        {
            "key1": {
                "name": "test2"
            }
        }
    ]
}

I would like to remove the object where key1.name: 'test2' from the data array.

I have tried the following:

db.Data.updateOne({}, { $pull: { 'data': { 'key1.name': 'test2' } } })

This works fine in a container instance of mongodb (latest).

But in a DocumentDB with engine version 5.0, it does not work and returns MongoServerError: Dotted field name is not valid for storage.

Is there any way for me to use the $pull operator in a DocumentDB where I’m targeting an object via a nested field?

2

Answers


  1. This doesn’t exactly answer how to use $pull for nested objects, but in DocumentDB you can use below workaround where you can try to set all such objects to null using update command array positional operator. You can write additional query to even clean this data array if required.

    db.Data.updateOne({"data.key1.name":"test"}, {$set: { "data.$[]":null}})
    
    Login or Signup to reply.
  2. DocumentDB is an emulation of MongoDB and may not support all the features in MongoDB.

    One of the workarounds at the moment could be using $filter to filter the data array and update back to the collection.

    db.collection.aggregate([
      {
        "$match": {
          "data.key1.name": "test2"
        }
      },
      {
        $set: {
          "data": {
            "$filter": {
              "input": "$data",
              "as": "d",
              "cond": {
                $ne: [
                  "$$d.key1.name",
                  "test2"
                ]
              }
            }
          }
        }
      }
    ]).forEach(function( result ) {
       db.collection.save(result);
    });
    

    Mongo Playground

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search