Bipul singh kashyap
Bipul singh kashyap

Reputation: 605

Get the names of all keys in nested documents of a MongoDB collection

I want to get all the keys from subdocuments in mongodb collection.

I tried $ObjectToArray it work for mongo shell but i want to achieve same using pymongo.

Mongodb collection named: collection

  {
    "_id": 0,
    "9": {
      "aam1": "a",
      "aam2": "b",
      "aam3": "c",
      "aam4": "ddd",
      "aam5": false,
      "aam6": {
        "aam1": "a",
        "aam2": "b",
        "aam3": "c",
        "aam4": "ddd",
        "aam5": false,
        "aam6": false
      },

    },
    "entity": "ask-me",
    "url": "",
    "createdDate": 21
  }
]

Mongo shell working code:

  {
    "$project": {
      "arrayofkeyvalue": {
        "$objectToArray": "$9.aam6"
      }
    }
  },
  {
    "$project": {
      "keys": "$arrayofkeyvalue.k"
    }
  }
])

I want to achieve above mongo shell working code using pymongo in python.

Upvotes: 0

Views: 374

Answers (1)

bagerard
bagerard

Reputation: 6354

I believe you need to use the aggregation framework from pymongo. Assuming c is your pymongo.Collection

pipeline = [
    {
    "$project": {
      "arrayofkeyvalue": {
        "$objectToArray": "$9.aam6"
      }
    }
  },
  {
    "$project": {
      "keys": "$arrayofkeyvalue.k"
    }
  }
]
print(list(c.aggregate(pipeline)))    # [{u'_id': 0, u'keys': [u'aam5', u'aam4', u'aam6', u'aam1', u'aam3', u'aam2']}]

Upvotes: 1

Related Questions