skip to Main Content

How to use $unset when a key contains dots in its name?

const key = "test"
const result = await db.collection(collection).updateOne(
    { [key]: { $exists: true } },
    { $unset: { [pathToKey]: 1 } }
);

given this document:

{
  "test": {
    "a": "b",         // <- test.a successfully erases the 'a' key
    "v0.0.1": "ok"    // <- test.v0.0.1 fails
  }
}

when pathToKey is 'test.a' it successfully erases the a key

when it 'test.v0.0.1' it fails, probably because the key contains a . in its name

I’m using the latest Mongo version

https://mongoplayground.net/p/Chiy7DtIqWb

I also tried using $unsetField: https://mongoplayground.net/p/MNyfhh1vdDW

2

Answers


  1. The keys with dots are not supported by MongoDB
    http://docs.mongodb.org/manual/reference/limits/#Restrictions-on-Field-Names

    Maybe you could use a workaround but i think it will be better to use different keys

    Login or Signup to reply.
  2. You can use $setField with $$REMOVE

    db.collection.aggregate([
      {
        "$match": {
          $expr: {
            $ne: [
              {
                "$ifNull": [
                  "$test",
                  {}
                ]
              },
              {}
            ]
          }
        }
      },
      {
        "$set": {
          "test": {
            "$setField": {
              "field": "v0.0.1",
              "input": "$test",
              "value": "$$REMOVE"
            }
          }
        }
      },
      {
        "$merge": {
          "into": "collection",
          "on": "_id"
        }
      }
    ])
    

    Mongo Playground


    For a nested object, chain up the above solution with $mergeObjects

    db.collection.aggregate([
      {
        "$set": {
          "test": {
            "$mergeObjects": [
              "$test",
              {
                "b": {
                  "$setField": {
                    "field": "b",
                    "input": "$test.b",
                    "value": "$$REMOVE"
                  }
                }
              }
            ]
          }
        }
      }
    ])
    

    Mongo Playground

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