2

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.

Tom Slabbaert
  • 21,288
  • 10
  • 30
  • 43
  • 1
    Does this answer your question? [mongodb query without field name](https://stackoverflow.com/questions/10901151/mongodb-query-without-field-name) – deadshot Apr 12 '21 at 04:45
  • your expected output `{"a","b","c"}` is not a valid json format, please provide valid format. – turivishal Apr 12 '21 at 05:32

1 Answers1

3

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

Tom Slabbaert
  • 21,288
  • 10
  • 30
  • 43