选择 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)
推荐答案
你需要$group
我们的文档并使用 $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屋!
查看全文