在一次 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 }
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP