为此,请在MongoDB中使用$$ROOT。让我们创建一个包含文档的集合-
> db.demo743.insertOne({id:1,"ShippingDate":"2020-01-21",value:50}); { "acknowledged" : true, "insertedId" : ObjectId("5ead893a57bb72a10bcf0680") } > db.demo743.insertOne({id:2,"ShippingDate":"2020-05-10",value:30}); { "acknowledged" : true, "insertedId" : ObjectId("5ead893c57bb72a10bcf0681") } > db.demo743.insertOne({id:3,"ShippingDate":"2020-05-10",value:60}); { "acknowledged" : true, "insertedId" : ObjectId("5ead894657bb72a10bcf0682") } > db.demo743.insertOne({id:1,"ShippingDate":"2020-05-11",value:75}); { "acknowledged" : true, "insertedId" : ObjectId("5ead895657bb72a10bcf0683") }
在find()方法的帮助下显示集合中的所有文档-
> db.demo743.find();
这将产生以下输出-
{ "_id" : ObjectId("5ead893a57bb72a10bcf0680"), "id" : 1, "ShippingDate" : "2020-01-21", "value" : 50 } { "_id" : ObjectId("5ead893c57bb72a10bcf0681"), "id" : 2, "ShippingDate" : "2020-05-10", "value" : 30 } { "_id" : ObjectId("5ead894657bb72a10bcf0682"), "id" : 3, "ShippingDate" : "2020-05-10", "value" : 60 } { "_id" : ObjectId("5ead895657bb72a10bcf0683"), "id" : 1, "ShippingDate" : "2020-05-11", "value" : 75 }
以下是根据它们与整个集合进行比较的方式提取整个文档的查询-
> db.demo743.aggregate([ ... { ... "$project": ... { ... "id": "$id", ... "ShippingDate": "$ShippingDate", ... "MyDoc": "$$ROOT" ... } ... }, ... { ... "$sort": ... { "ShippingDate": -1 ... } ... }, ... { ... "$group": ... { ... "_id":{"id":"$id"}, ... "Result":{"$first":"$MyDoc"} ... } ... }, ... { ... $project: ... { ... "Result.ShippingDate":1, "Result.id":1, "Result.value":1, _id:0} ... } ... ])
这将产生以下输出-
{ "Result" : { "id" : 3, "ShippingDate" : "2020-05-10", "value" : 60 } } { "Result" : { "id" : 2, "ShippingDate" : "2020-05-10", "value" : 30 } } { "Result" : { "id" : 1, "ShippingDate" : "2020-05-11", "value" : 75 } }