选择2个字段并返回具有其不同值的排序数组 [英] select 2 fields and return a sorted array with their distinct values
本文介绍了选择2个字段并返回具有其不同值的排序数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
说我们有以下文档:
{a: 1, b: 2},
{a: 2, b: 0},
{a: 3, b: 1}
我想要一个查询,该查询将返回:
I want a query that will return:
[0, 1, 2, 3]
我想知道是否有比以下方法更快的方法:
I want to know if there is a way to do this faster than:
- 仅进行2个查询,一个选择
a
,另一个选择b
,然后合并到我的应用程序中. - 使用map reduce(与以前的方法相比,速度很慢)
- just making 2 queries, one selecting
a
, the other selectingb
then merging in my application. - using map reduce(which was reaaaaly slow compared to the previous method)
推荐答案
您需要 $push
累加器运算符可返回集合中的"a"和"b"数组.
You need to $group
our documents and use the $push
accumulator operator to return an array of "a" and "b" within the collection.
在 $project
运算符中,您使用 $setUnion
运算符,以过滤出重复项.
In the $project
operator you use the $setUnion
operator to filter out the duplicates.
db.coll.aggregate(
[
{ "$group": {
"_id": null,
"a": { "$push": "$a" },
"b": { "$push": "$b" }
}},
{ "$project": {
"_id": 0,
"merged": { "$setUnion": [ "$a", "$b" ] }
}}
]
)
产生:
{ "merged" : [ 3, 2, 0, 1 ] }
这篇关于选择2个字段并返回具有其不同值的排序数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文