SexyMF
SexyMF

Reputation: 11165

Mongodb distinct on a key in a key value pair situation

I have the bellow document structure in mongodb, I want to bring distinct keys from the column customData So if you look bellow, I want my result to be: key1,key2,key3,key4

doing

db.coll.distinct("customData")

will bring the values and not the keys.

{
   "_id":ObjectId("56c4da4f681ec51d32a4053d"),
   "accountUnique":7356464,
   "customData":{
      "key1":1,
      "key2":2,
   }
}

{
   "_id":ObjectId("56c4da4f681ec51d32a4054d"),
   "accountUnique":7356464,
   "customData":{
      "key3":1,
      "key4":2,
   }
}

Upvotes: 1

Views: 371

Answers (1)

chridam
chridam

Reputation: 103375

Possible to do this with Map-Reduce since you have dynamic subdocument keys which the distinct method will not return a result for.

Running the following mapreduce operation will populate a separate collection with all the keys as the _id values:

var myMapReduce = db.runCommand({
    "mapreduce": "coll",
    "map" : function() {
        for (var key in this.customData) { emit(key, null); }
    },
    "reduce" : function() {}, 
    "out": "coll_keys"
})

To get a list of all the dynamic keys, run distinct on the resulting collection:

db[myMapReduce.result].distinct("_id")

will give you the sample output

["key1", "key2", "key3", "key4"]

Upvotes: 2

Related Questions