从Mongo文档中获取所有阵列的值
我有一个包含数组的文档的Mongo集合:
{ item: "journal", qty: 25, tags: ["blank", "red"], dim_cm: [ 14, 21 ] },
{ item: "notebook", qty: 50, tags: ["red", "blank"], dim_cm: [ 14, 21 ] },
{ item: "paper", qty: 100, tags: ["red", "blank", "plain"], dim_cm: [ 14, 21 ] },
{ item: "planner", qty: 75, tags: ["blank", "red"], dim_cm: [ 22.85, 30 ] },
{ item: "postcard", qty: 45, tags: ["blue"], dim_cm: [ 10, 15.25 ] }
我想获得一个包含所有不同值的单个数组,例如:
[blank“”,“ red”,“ red”,“ blue”]和dim_cm:[14,21,22.85, 30,10,15.25]
这是通过聚合管道的?
I have a mongo collection with documents containing arrays:
{ item: "journal", qty: 25, tags: ["blank", "red"], dim_cm: [ 14, 21 ] },
{ item: "notebook", qty: 50, tags: ["red", "blank"], dim_cm: [ 14, 21 ] },
{ item: "paper", qty: 100, tags: ["red", "blank", "plain"], dim_cm: [ 14, 21 ] },
{ item: "planner", qty: 75, tags: ["blank", "red"], dim_cm: [ 22.85, 30 ] },
{ item: "postcard", qty: 45, tags: ["blue"], dim_cm: [ 10, 15.25 ] }
I would like to get a single array containing all distinct values, such as:
tags: ["blank", "red", blue"] and dim_cm: [14,21,22.85,30,10,15.25]
Is this possible with an aggregation pipeline?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
$ group
与$降低
和$ setIntersection
:$ group
所有文档都创建一个数组每个键$降低
将每个数组弄平,并使用$ setIntersection
使其成为集合。查看其在
工作
方式/mongoplayground.net/p/udm4omq9lqv“ rel =“ nofollow noreferrer”> playground -undind
您可以将它们分为两个查询,这将更快:
第三选项是:
Playground 3rd
You can use
$group
with$reduce
and$setIntersection
:$group
all documents to create one array of arrays per key$reduce
and make it a set using$setIntersection
.See how it works on the playground example
Another way is:
Playground - unwind
Which you can split into two queries which will be much faster:
A 3rd option is:
Playground 3rd
查询
*此类类型是不同的,如果它们是相同类型的类型,我们可以做另一个技巧,例如将Pairs
[[[TAG,CM] ...]
首先是标签,第二个是CM或文档数组如果您可以测试,则如果可以
Query
*here types are different, in case they were the same type, we can do another trick like put the in an array of pairs
[[tag,cm] ...]
where first would be the tag and the second would be the cm, or array of documentsFor perfomance if you test it send how it went if you can
Playmongo