$ setUnion合并来自多个文档MongoDB的数组

编程入门 行业动态 更新时间:2024-10-21 03:43:41
本文介绍了$ setUnion合并来自多个文档MongoDB的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在一个集合中有以下文档:

I have documents in a collection as follows :

{ _id : 1 , data : [7,4,0] } { _id : 2 , data : [4,5,6] } { _id : 3 , data : [6,7,8] }

我想合并两个或更多文档中的data数组.

I want to union the data array from two or more documents.

我用来查找id 1和2的data数组的并集的查询是:

The query I am using to find the union of data array of id 1 and 2 is:

db.coll.aggregate( { $match : { _id: { $in: [1, 2] } } }, { $group: { _id: 0, s0: { $first: "$data"}, s1: { $first: "$data"} } }, { $project: { _id: 0, ans: { $setUnion: [ "$s0","$s1"]} } } ).pretty()

但查询结果为:

{7, 5, 0}

似乎仅是id 1的数据.

如何在同一阵列上的两个或多个文档之间实现联合 场?

How to achieve the union between two or more documents on same array field?

PS:我正在使用MongoDB 3.4

推荐答案

有关更有效的查询,请使用 $reduce 运算符以展平数组.这将允许您连接任意数量的数组,因此,不仅仅是将文档1和2中的两个数组进行并集,这也将适用于其他数组.

For a more efficient query, use the $reduce operator to flatten the arrays. This will allow you to concat any number of arrays, so instead of just doing a union of the two arrays from docs 1 and 2, this will also apply for other arrays as well.

考虑运行以下聚合操作:

Consider running the following aggregate operation:

db.coll.aggregate([ { "$match": { "_id": { "$in": [1, 2] } } }, { "$group": { "_id": 0, "data": { "$push": "$data" } } }, { "$project": { "data": { "$reduce": { "input": "$data", "initialValue": [], "in": { "$setUnion": ["$$value", "$$this"] } } } } } ])

示例输出

{ "_id" : 0, "data" : [ 0, 4, 5, 6, 7 ] }

更多推荐

$ setUnion合并来自多个文档MongoDB的数组

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

发布评论

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

>www.elefans.com

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