Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mongodb聚合能否基于日期从子文档数组中投影单个子文档?_Mongodb_Aggregation Framework_Mongodb Aggregation - Fatal编程技术网

Mongodb聚合能否基于日期从子文档数组中投影单个子文档?

Mongodb聚合能否基于日期从子文档数组中投影单个子文档?,mongodb,aggregation-framework,mongodb-aggregation,Mongodb,Aggregation Framework,Mongodb Aggregation,假设有一组人员,每个人都有一组位置子文档,其中一些包含“未来”位置: { "_id" : 1, "name": "Homer", "itinerary": [ { date: "...", "location": "Springfield" }, { date: "...", "location": "London" } ] } { "_id" : 2, "name": "Bart", "itinerary": [ { date: "...", "location": "Las Vegas" }

假设有一组人员,每个人都有一组位置子文档,其中一些包含“未来”位置:

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

您可以从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

您可以在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