在一次 MongoDB 聚合查询中进行排序和分组?


要对单个查询进行排序和分组,请使用聚合框架以及 $group 运算符。我们先用文档创建一个集合 -

> db.sortAndGroupDemo.insertOne({
   Price :40,
   Product: 10
});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ce8f2bc78f00858fb12e907")
}
> db.sortAndGroupDemo.insertOne({
   Price :100,
   Product: 10
});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ce8f2bc78f00858fb12e908")
}
> db.sortAndGroupDemo.insertOne({
   Price :90,
   Product: 20
});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ce8f2bc78f00858fb12e909")
}
> db.sortAndGroupDemo.insertOne({
   Price :200,
   Product: 10
});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ce8f2bc78f00858fb12e90a")
}
> db.sortAndGroupDemo.insertOne({
   Price :70,
   Product: 20
});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ce8f2bc78f00858fb12e90b")
}
> db.sortAndGroupDemo.insertOne({
   Price :70,
   Product: 30
});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ce8f2bd78f00858fb12e90c")
}

以下是查询,将使用 find() 方法,以显示某个集合中的所有文档 -

> db.sortAndGroupDemo.find().pretty();

这将会产生以下输出 -

{
   "_id" : ObjectId("5ce8f2bc78f00858fb12e907"),
   "Price" : 40,
   "Product" : 10
}
{
   "_id" : ObjectId("5ce8f2bc78f00858fb12e908"),
   "Price" : 100,
   "Product" : 10
}
{
   "_id" : ObjectId("5ce8f2bc78f00858fb12e909"),
   "Price" : 90,
   "Product" : 20
}
{
   "_id" : ObjectId("5ce8f2bc78f00858fb12e90a"),
   "Price" : 200,
   "Product" : 10
}
{
   "_id" : ObjectId("5ce8f2bc78f00858fb12e90b"),
   "Price" : 70,
   "Product" : 20
}
{
   "_id" : ObjectId("5ce8f2bd78f00858fb12e90c"),
   "Price" : 70,
   "Product" : 30
}

以下是查询,将在一个 MongoDB 聚合查询中进行排序和分组 -

> db.sortAndGroupDemo.aggregate(
   [
      { "$group": { "_id": "$Product" }},
      { "$sort" : { "Price": 1 }},
      { "$project":{"_id":1 }}
   ]
);

这将会产生以下输出 -

{ "_id" : 30 }
{ "_id" : 20 }
{ "_id" : 10 }

更新于: 2019 年 7 月 30 日

670 次查看

开启你的 职业生涯

完成课程获取认证

开始
广告
© . All rights reserved.