如何连接来自 MongoDB 中多个文档的数组? [英] How to concatenate arrays from multiple documents in MongoDB?
本文介绍了如何连接来自 MongoDB 中多个文档的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个名为people"的集合,其中包含以下文档:
Let's say I have a collection called 'people' with the following documents:
{
"name": "doug",
"colors": ["blue", "red"]
}
{
"name": "jack",
"colors": ["blue", "purple"]
}
{
"name": "jenny",
"colors": ["pink"]
}
我如何获得所有 colors
子数组的串联数组,即?
How would I get a concatenated array of all the colors
subarrays, i.e.?
["blue", "red", "blue", "purple", "pink"]
推荐答案
尝试使用聚合:
db.people.aggregate([
{$unwind:"$colors"},
{$group:{_id:null, clrs: {$push : "$colors"} }},
{$project:{_id:0, colors: "$clrs"}}
])
结果:
{
"result" : [
{
"colors" : [
"blue",
"red",
"blue",
"purple",
"pink"
]
}
],
"ok" : 1
}
更新
如果你想在结果的数组中获得唯一值,你可以使用 $addToSet 运算符而不是 $group
阶段中的 $push
.
If you want to get unique values in result's array, you could use $addToSet operator instead of $push
in the $group
stage.
这篇关于如何连接来自 MongoDB 中多个文档的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文