为此,请使用$project和aggregate()。聚合中的$project将带有请求字段的文档传递到管道的下一个阶段。
让我们创建一个包含文档的集合-
> db.demo762.insertOne({ ... "_id" : { ... "userId":101, ... "userName":"Chris" ... }, .. . "countryName" : "US", ... ... "details" : [ ... { ... "Name" : "Robert", ... "DueDate" : "2020-04-10" ... ... }, ... ... { ... "Name" : "Robert", ... "DueDate" : "2020-04-09" ... }, ... { ... "Name" : "Robert", ... "DueDate" : "2020-03-06" ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : { "userId" : 101, "userName" : "Chris" } }
在find()方法的帮助下显示集合中的所有文档-
> db.demo762.find();
这将产生以下输出-
{ "_id" : { "userId" : 101, "userName" : "Chris" }, "countryName" : "US", "details" : [ { "Name" : "Robert", "DueDate" : "2020-04-10" }, { "Name" : "Robert", "DueDate" : "2020-04-09" }, { "Name" : "Robert", "DueDate" : "2020-03-06" } ] }
以下是对MongoDB聚合和投影的查询-
> db.demo762.aggregate([ ... { "$match": { ... "_id": { "$eq": { userId:101,userName:"Chris" }} ... }}, ... { "$unwind": "$details" }, ... { "$sort": { "details.DueDate": 1 }}, ... { "$group": { ... "_id": "$_id", ... "details": { "$push": "$details" }, ... "countryName": { "$first": "$countryName" } ... }}, ... { "$project": { "details": { "$slice": ["$details", 2] } ,"countryName": 1 }} ... ]).pretty();
这将产生以下输出-
{ "_id" : { "userId" : 101, "userName" : "Chris" }, "countryName" : "US", "details" : [ { "Name" : "Robert", "DueDate" : "2020-03-06" }, { "Name" : "Robert", "DueDate" : "2020-04-09" } ] }