要在单个查询中进行排序和分组,请使用$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 }