Get the keys corresponding to a value in MongoDB

Viewed 27

I have a document inside my Mongodb collection, something like this :

{
 "a": "Bahrain",
 "b": "Bahrain",
 "c": "Bahrain",
 "d": "Oman",
 "e": "Oman",
 "f": "Oman"
}

What I want is to get the keys corresponding to a value i.e query by the values.

Eg. For value Bahrain, I want to get {"a","b","c"} as the output.

1 Answers

You'll need to transform the $$ROOT variable to an array. then filter it according to the condition you want, like so:

db.collection.aggregate([
  {
    $match: { _id: docId }
  },
  {
    $project: {
      fieldKeys: {
        $map: {
          input: {
            $filter: {
              input: {
                "$objectToArray": "$$ROOT"
              },
              as: "datum",
              cond: {
                $eq: [
                  "$$datum.v",
                  "Bahrain"
                ]
              }
            }
          },
          as: "key",
          in: "$$key.k"
        }
      }
    }
  }
])

Mongo Playground

Related