Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve distinct keys inside an object in MongoDB

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?

like image 911
Carlos Avatar asked Mar 09 '23 06:03

Carlos


1 Answers

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 }]}
like image 194
s7vr Avatar answered Mar 12 '23 10:03

s7vr