在mongo聚合中选择*分组依据 [英] Select * group by in mongo aggregation
问题描述
我正在尝试做一些我认为非常简单的事情.假设我在mongo中有一系列记录,这些记录具有一个公用键和可变数量的属性.我想选择所有属性并在记录中按名称分组.例如
I am trying to do something that I think is quite simple. Suppose I have a series of records in mongo that have a common key, and variable number of attributes. I want to select all attributes and group by name across the records. For example
{ Name: George, x: 5, y: 3 }
{ Name: George, z: 9 }
{ Name: Rob, x: 12, y: 2 }
我想生成一个如下所示的CSV文件:
I would like to produce a CSV that looks like this:
Name X Y Z
George 5 3 9
Rob 12 2
尝试
DB.data.aggregate({ $group : { _id : "$Name" } })
不幸的是,我取回了所有名称作为记录,但没有取回所有可能属性的并集.
Unfortunately I get back all the names as records but not the union of all the possible attributes.
推荐答案
如果要合并属性,则需要将这些属性添加到group
中.例如,使用 $addToSet
查找x的唯一值, y,z属性按每个名称分组:
If you want to combine the attributes, you'll need to add those to the group
. For example, using $addToSet
to find the unique values of the x,y,z attributes grouped by each name:
db.data.aggregate(
{ $group : {
_id : "$Name",
x: { $addToSet: "$x" },
y: { $addToSet: "$y" },
z: { $addToSet: "$z" },
}}
)
返回:
{
"result" : [
{
"_id" : "Rob",
"x" : [
12
],
"y" : [
2
],
"z" : [ ]
},
{
"_id" : "George",
"x" : [
5
],
"y" : [
3
],
"z" : [
9
]
}
],
"ok" : 1
}
这篇关于在mongo聚合中选择*分组依据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!