MongoDB 聚合和投影?
为此,请将 $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" } ] }
广告