是否可以根据最大值对数据进行排序。来自该组的价值。 数据:
> db.test.find({})
{"a" : 1, "d" : 10 }
{"a" : 1, "d" : 1 }
{"a" : 2, "d" : 50 } // changed, it was initially ({"a" : 2, "d" : 20 })
{"a" : 2, "d" : 2 }
{"a" : 3, "d" : 30 }
{"a" : 3, "d" : 4 }
{"a" : 1, "d" : 10 }
结果:
a:2,d:50 | a:2:d:2 | a:3,d:30 | a:3,d:4 | a:1,d:10 | a:1,d:10 | a:1,d 1
SQL等价物:
create table test(a integer, d integer);
insert into test
select 3, 30 union all
select 3, 4 union all
select 2, 20 union all
select 2, 2 union all
select 1, 10 union all
select 1, 10 union all
select 1, 1;
select a, d, max(d) over (partition by a) as max_in_group
from test
order by 3 desc, 2 desc;
或
select *
from test t
inner join
(
select a, max ( d ) as max_d
from test
group by a
)X on t.a = x.a
order by max_d desc, d desc
感谢。
答案 0 :(得分:1)
db.coll.aggregate(
{$sort: {d: -1}},
{$group: {_id: "$a", d: {$push: "$d"}, max: {$max: "$d"}}},
{$sort: {max: -1}},
{$unwind: "$d"},
{$project: {a: "$_id", d: 1, _id: false}}
);
结果:
{ "d" : 30, "a" : 3 }
{ "d" : 4, "a" : 3 }
{ "d" : 20, "a" : 2 }
{ "d" : 2, "a" : 2 }
{ "d" : 10, "a" : 1 }
{ "d" : 10, "a" : 1 }
{ "d" : 1, "a" : 1 }
P.S。:如果您不在组内处理订单,您可以删除第一个管道阶段{$sort: {d: -1}}
;你会得到下一个结果:
{ "d" : 30, "a" : 3 }
{ "d" : 4, "a" : 3 }
{ "d" : 20, "a" : 2 }
{ "d" : 2, "a" : 2 }
{ "d" : 10, "a" : 1 }
{ "d" : 1, "a" : 1 } // <-- not
{ "d" : 10, "a" : 1 } // <-- ordered