Home > Back-end >  MongoDB query: delete entry if any nested object within object has value for key
MongoDB query: delete entry if any nested object within object has value for key

Time:04-23

Say I have the following entry:

{
  name: 'Bob',
  a: {
    02910143: { val: 10 },
    101B70BB: { val: 20 },
    7A6C86F1: { val: 10 },
  }
}

Note that the keys for object a are hashes, so I don't know the names of them for my query. I'm trying to write my query that will delete all entries where val is 10. I have the following, but I can't seem to figure out how to go through all of the nested objects:

db.collection('myCollection').deleteMany({ 'a.$.val': 10 })

How do I make it such that it'll check any key-value entry in a?

CodePudding user response:

You can use $arrayToObject to convert a into an array of k-v tuple first. Then use $filter to remove the value not equal to 10. Finally convert back to original form using $arrayToObject

db.collection.aggregate([
  {
    "$addFields": {
      "a": {
        "$objectToArray": "$a"
      }
    }
  },
  {
    "$addFields": {
      "a": {
        "$filter": {
          "input": "$a",
          "as": "a",
          "cond": {
            $ne: [
              "$$a.v.val",
              10
            ]
          }
        }
      }
    }
  },
  {
    "$addFields": {
      "a": {
        "$arrayToObject": "$a"
      }
    }
  }
])

Here is the Mongo playground for your reference.

  • Related