1

假设一个人的集合,每个人都有一个位置子文档的集合,其中一些包括“未来”位置:

{ "_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" } ] }

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

{ "_id" : 1, "name": "Homer", "currentLocation": { date: "...", "location": "Springfield" } }
{ "_id" : 2, "name": "Bart", "currentLocation": { date: "...", "location": "Houston" } }
{ "_id" : 3, "name": "Marge", "currentLocation": { date: "...", "location": "Washington" } }
{ "_id" : 4, "name": "Lisa", "currentLocation": { date: "...", "location": "Paris" } }
4

1 回答 1

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改为使用。

于 2019-10-18T09:38:31.897 回答