假设我们有一系列文档如下:
[
{
"name" : "john",
"age" : 23,
"city": "New York",
"gender": "M"
},
{
"name" : "doe",
"age" : 30,
"city": "dubai",
"gender": "M"
},
{
"name" : "jean",
"age" : 23,
"city": "New York",
"gender": "F"
}
{
"name" : "phil",
"age" : 24,
"city": "Ohio",
"gender": "M"
}
]
预期产出:
{
"name" : ["john","doe","jean","phil"],
"age" : [23,30,24],
"city": ["New York","Dubai","Ohio"],
"gender": ["M","F"]
}
我尝试使用mongodb的distinct,但是这将返回一个特定字段的唯一值...我不认为我们可以在不同的查询中传递多个字段...
答案 0 :(得分:6)
$addToSet专门针对这类事情。
db.coll.aggregate([
{$group: {
_id: null,
name: {$addToSet: '$name'},
age: {$addToSet: '$age'},
city: {$addToSet: '$city'},
gender: {$addToSet: '$gender'}
}}
])
给出了输出 -
{ "_id" : null, "name" : [ "phil", "jean", "doe", "john" ], "age" : [ 24, 30, 23 ], "city" : [ "Ohio", "dubai", "New York" ], "gender" : [ "F", "M" ] }