mongodb聚合中将多个数组合并成一个数组

需求

有时候,我们需要在查询结果中将某个字段(其类型是数组)合并起来,仅返回一个数组。

例子

假设集合 user

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// 小明
{
"_id" : ObjectId("5eb6bb5bc95fdd10d0f6d21e"),
"name" : "小明",
"education" : "本科",
"experiences" : [
{
"profession" : "程序员",
"ability" : [
"java",
"nodejs",
"golang"
]
}
]
}
// 小红
{
"_id" : ObjectId("5eb6bbdbc95fdd10d0f6d220"),
"name" : "小红",
"education" : "本科",
"experiences" : [
{
"profession" : "销售",
"ability" : [
"沟通",
"财务计算"
]
},
{
"profession" : "采购员",
"ability" : [
"英语",
"统计"
]
}
]
}
// 小三
{
"_id" : ObjectId("5eb6bdbbc95fdd10d0f6d23f"),
"name" : "小三",
"education" : "大专",
"experiences" : [
{
"profession" : "行政助理",
"ability" : [
"英语"
]
}
]
}

接下来我想查询出所有学历为 本科 的阅历(experiences)列表,并把它们合并成一个数组返回,返回期望结果如下:

1
2
3
4
5
6
7
8
{ 
"_id" : "1",
"experiences" : [
{ "profession" : "销售", "ability" : ["沟通", "财务计算"] },
{ "profession" : "采购员", "ability" : ["英语", "统计"]},
{ "profession" : "程序员", "ability" : ["java", "nodejs", "golang"]}
]
}

Aggregate 实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
db.getCollection("user").aggregate(
[
{
"$match" : { "education" : "本科" }
},
{
"$group" : {
"_id" : "1",
"experiences" : {
"$addToSet" : "$experiences"
}
}
},
{
"$project" : {
"experiences" : {
"$reduce" : {
"input" : "$experiences",
"initialValue" : [],
// this 是指每个迭代的数组元素,value 指上一次操作的结果值
"in" : { "$concatArrays" : ["$$value", "$$this"] }
}
}
}
}
]
)

参考

本文摘抄至以下文章,在此表示诚挚感谢!

  1. mongo 使用聚合合并字段

  2. https://docs.mongodb.com/manual/reference/operator/aggregation/reduce/