如何在MongoDB中检索对象内部的不同键 [英] How to retrieve distinct keys inside an object in MongoDB
问题描述
我在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:
我想在每个文档的索引"对象中获取不同的键.
我想要得到的结果是:["Citroen", "color", "Marca", "rojo", "blancos", "ocasión", "Madrid", "Coches", "coches", "rojos", "Ocasión", "marcas", "blancas" "autos", "de"]
.
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?
推荐答案
您可以使用新的 $ 3.4.4 中的objectToArrray 版本以转换所有键&值对放入文档数组,后跟$unwind
& $group
和$addToSet
以获得不同的键
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"}}}])
对于较低版本,您必须将indexation
更新为如下所示,并使用
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 }]}
这篇关于如何在MongoDB中检索对象内部的不同键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!