在MongoDB聚合中解除$ unwind后删除重复键

时间:2016-02-16 03:01:30

标签: mongodb aggregation-framework

使用MongoDB,我在包含名为tests的数组的文档上执行聚合管道,并使用$unwind操作将该数组展开为多个文档:

原始文件:

{"_id"=>"1867930", "tests"=> [
    {"status"=>"passed", "elapsed_time"=>26, "worker"=>11},
    {"status"=>"passed", "elapsed_time"=>34, "worker"=>13},
    {"status"=>"passed", "elapsed_time"=>23, "worker"=>15}
]}

$unwind之后的结果:

{"_id"=>"1867930", "tests"=>{"status"=>"passed", "elapsed_time"=>26, "worker"=>11}}
{"_id"=>"1867930", "tests"=>{"status"=>"passed", "elapsed_time"=>34, "worker"=>13}}
{"_id"=>"1867930", "tests"=>{"status"=>"passed", "elapsed_time"=>23, "worker"=>15}}

如何应用其他操作将每个文档中的tests键的值提升到一个级别(即消除从tests创建的重复$unwind个键)到得到以下结果?

{"_id"=>"1867930", "status"=>"passed", "elapsed_time"=>26, "worker"=>11}
{"_id"=>"1867930", "status"=>"passed", "elapsed_time"=>34, "worker"=>13}
{"_id"=>"1867930", "status"=>"passed", "elapsed_time"=>23, "worker"=>15}

请注意,这是重命名tests密钥,它会将tests的值向上移动一级并与父哈希值合并。

1 个答案:

答案 0 :(得分:1)

尝试通过$project

进行操作
db.collection.aggregate([
  {$unwind: '$tests'}, 
  {$project: 
     {status: '$tests.status', 
      elapsed_time: '$tests.elapse_time',
      worker: '$tests.worker'}}
]);

或者使用光标forEach执行以下操作以打印数据格式

db.collection.find({ "tests": {"$exists": 1 }}).forEach(
   function(doc){
      for (var i in doc.tests){
         doc.tests[i]._id = doc._id; 
         printjson(doc.tests[i]);
      }
   });