Mongodb聚合可以根据日期从子文档数组中生成单个子文档吗?

时间:2016-08-07 18:48:44

标签: mongodb aggregation-framework mongodb-aggregation

假设一组People,每个人都有一组位置子文档,其中一些包括" future"位置:

next

是否有可能编写一个mongodb聚合,返回每个人截至今天的位置:

{ "_id" : 1, "name": "Homer", "itinerary": [ { date: "...", "location": "Springfield" }, { date: "...", "location": "London" } ] }
{ "_id" : 2, "name": "Bart", "itinerary": [ { date: "...", "location": "Las Vegas" }, { date: "...", "location": "Houston" } ] }
{ "_id" : 3, "name": "Marge", "itinerary": [ { date: "...", "location": "Washington" }, { date: "...", "location": "Springfield" } ] }
{ "_id" : 4, "name": "Lisa", "itinerary": [ { date: "...", "location": "London" }, { date: "...", "location": "Paris" } ] }

1 个答案:

答案 0 :(得分:0)

您可以从mongo 3.2开始执行此操作:

db.collection.aggregate([{
  $match: {...}
}, {
  $set: {
    "currentLocation": {
       $arrayElemAt: [
         {$filter: 
           {input: "$itinerary", cond: {$eq: ["$$this.date", "present"]}}
         }, 
       0]
    }
  }
}, {
  $unset: {"itinerary": 1}
}]);

$unset$set已在4.2中添加,但您可以改用$project