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
@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.
what should be the expected output?
– Anthony Winzlet
Sep 13 '18 at 10:26