使用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
的值向上移动一级并与父哈希值合并。
答案 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]);
}
});