在MongoDB聚合中使用$sort。让我们创建一个包含文档的集合-
> db.demo652.insertOne({ ... value:10, ... "details" : [{ ... "ProductName" : "Product-1", ... "ProductQuantity" : 8, ... "ProductPrice" : 500 ... }, { ... "ProductName" : "Product-2", ... "ProductQuantity" : 7, ... "ProductPrice" : 500 ... ... }] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e9f0730e3c3cd0dcff36a62") } > > db.demo652.insertOne({ ... value:5, ... "details" : [{ ... "ProductName" : "Product-1", ... "ProductQuantity" : 8, ... "ProductPrice" : 500 ... }, { ... "ProductName" : "Product-2", ... "ProductQuantity" : 7, ... "ProductPrice" : 500 ... ... }] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e9f0740e3c3cd0dcff36a63") }
在find()方法的帮助下显示集合中的所有文档-
> db.demo652.find();
这将产生以下输出-
{ "_id" : ObjectId("5e9f0730e3c3cd0dcff36a62"), "value" : 10, "details" : [ { "ProductName" : "Product-1", "ProductQuantity" : 8, "ProductPrice" : 500 }, { "ProductName" : "Product-2", "ProductQuantity" : 7, "ProductPrice" : 500 } ] } { "_id" : ObjectId("5e9f0740e3c3cd0dcff36a63"), "value" : 5, "details" : [ { "ProductName" : "Product-1", "ProductQuantity" : 8, "ProductPrice" : 500 }, { "ProductName" : "Product-2", "ProductQuantity" : 7, "ProductPrice" : 500 } ] }
以下是按升序排序的查询-
> db.demo652.aggregate([{ ... "$unwind": "$details" ... }, { ... "$match": {} ... }, { ... "$group": { ... "ProductPrice": { ... "$first": "$value" ... }, ... "details": { ... "$push": { ... "ProductName": "$details.ProductName" ... } ... }, ... "_id": "$_id" ... } ... }, { ... "$sort": { ... "ProductPrice": 1 ... } ... }, { ... "$project": { ... "_id": 0, ... "ProductPrice": 1, ... "details": 1 ... } ... }]).pretty()
这将产生以下输出-
{ "ProductPrice" : 5, "details" : [ { "ProductName" : "Product-1" }, { "ProductName" : "Product-2" } ] } { "ProductPrice" : 10, "details" : [ { "ProductName" : "Product-1" }, { "ProductName" : "Product-2" } ] }