在一次 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 }
廣告