Home > Software design >  MongoDB delete fields with unknown names, based on value
MongoDB delete fields with unknown names, based on value

Time:12-15

I have something like this:

{
  "_id": ...,
  "section": {
    "a": "101",
    "b": "101",
    "c": "000",
    "d": "101"
  }
}

How can I unset all fields with value "101"? I know nothing about keys ("a", "b", "c"), only value.

CodePudding user response:

Query

  • schema in general must be known even if some fields are missing, so having unknown schema is not good idea
  • uknown schema causes many problems and slower, more complicated queries, but you still can do it with objectToAray arrayToObject etc

Playmongo

aggregate(
[{"$set": 
   {"section": 
     {"$arrayToObject": 
       [{"$filter": 
           {"input": {"$objectToArray": "$section"},
            "cond": {"$ne": ["$$this.v", "101"]}}}]}}}])
  • Related