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

Ken Liu

使用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并与父哈希合并。

zangw

尝试通过 $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]);
      }
   });

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章