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:
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?
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 }]}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With