4

I have this in MongoDB:

{ "_id" : ObjectId("58fb35531eb5df245d5d434f"), "name" : "d1.html", "indexation" : { "Citroen" : 1, "color" : 1, "Marca" : 1, "rojo" : 1 } }
{ "_id" : ObjectId("58fb35531eb5df245d5d4350"), "name" : "d2.html", "indexation" : { "blancos" : 1, "ocasión" : 1, "Madrid" : 1, "Coches" : 1, "rojo" : 1, "coches" : 1 } }
{ "_id" : ObjectId("58fb35531eb5df245d5d4351"), "name" : "d3.html", "indexation" : { "rojos" : 1, "Ocasión" : 1, "marcas" : 1, "Madrid" : 1, "blancas" : 1, "autos" : 1, "de" : 1 } }

You can see an image containing the above: Content

And I would like to get the distinct keys inside the object "indexation" in each document. The result I woul like to get is: ["Citroen", "color", "Marca", "rojo", "blancos", "ocasión", "Madrid", "Coches", "coches", "rojos", "Ocasión", "marcas", "blancas" "autos", "de"].

I'm trying with distinct ("indexation") but I get the whole indexation...

Could you explain to me what do I have to do to get what I want, please?

Carlos
  • 293
  • 1
  • 5
  • 16

1 Answers1

7

You can use new $objectToArrray in 3.4.4 version to convert all key & value pair into document arrays followed by $unwind & $group with $addToSet to get distinct keys

db.collection.aggregate([{$project: {indexation: {$objectToArray: "$indexation"}}}, {$unwind:"$indexation"}, {$group:{_id:null, keys:{$addToSet:"$indexation.k"}}}])

For lower version you've to update indexation to look like below and and use

db.collection.distinct("indexation.k")

 { "_id" : ObjectId("58fb35531eb5df245d5d434f"), "name" : "d1.html", "indexation" : [{ "k" : "Citroen", "v" : 1 }, { "k" : "Marca", "v" : 1 }]}
s7vr
  • 73,656
  • 11
  • 106
  • 127
  • How do I modify `indexation` to make it look like `[{ "k" : "Citroen", "v" : 1 }, { "k" : "Marca", "v" : 1 }]`? @Veeram – Carlos Apr 22 '17 at 14:58
  • Its two part change. Converting from object to array and bulk update(depending on number of documents) or simple iteration. Use http://stackoverflow.com/questions/38824349/convert-object-to-array-in-javascript for conversion and use http://stackoverflow.com/questions/33530357/loop-through-mongo-collection-and-update-a-field-in-every-document/ for bulk upload. – s7vr Apr 22 '17 at 15:11