mongodb distinct the key of a map in an array which is a property of a document

mongodb distinct the key of a map in an array which is a property of a document



I use mongodb,one document format is like this:



sid:2,
attr:[

key:"name",
value:"bike"
,
key:"weight",
value:"100"

]



there is a property "attr" which is like a map with uncertain number of keys.
the whole collection look like this:


[
sid:1,
attr:[

key:"name",
value:"bike"

]
,
sid:2,
attr:[

key:"name",
value:"bike"
,
key:"weight",
value:"100"

]
,
sid:3,
attr:[

key:"color",
value:"red"
,
key:"weight",
value:"100"

]
]



Now, what I want to know is how many distinct keys there are,and what are them.
In this example,the distinct keys I expected should be:


["name","weight","color"]



but what about more document inserted into the collection?The data in this collection is not fixed






what should be the expected output?

– Anthony Winzlet
Sep 13 '18 at 10:26






@AnthonyWinzlet: ["name","weight","color"]

– hometown
Sep 13 '18 at 10:28






@AnthonyWinzlet thanks a lot.It works.I will learn the api and verify if it is accurate later

– hometown
Sep 13 '18 at 10:35






Try db.colname.distinct("attr.key")

– Veeram
Sep 13 '18 at 10:55


db.colname.distinct("attr.key")






I tried,get a 57 result in my real table.the number is more,I need to check @Veeram

– hometown
Sep 13 '18 at 11:23




1 Answer
1



You need to first $unwind the attr array then you can use $group aggregation to distinct the fields.


$unwind


attr


$group


db.collection.aggregate([
"$unwind": "$attr" ,
"$group": "_id": "$attr.key"
])



Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)