如何连接来自 MongoDB 中多个文档的数组?

编程入门 行业动态 更新时间:2024-10-24 02:37:48
本文介绍了如何连接来自 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 中多个文档的数组?

本文发布于:2023-11-22 18:39:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1618553.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   数组   文档   MongoDB

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!