使用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
并与父哈希合并。
尝试通过 $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] 删除。
我来说两句