2016-02-16 26 views
1

使用MongoDB中,我针对的是包含一个名为tests阵列文档的集合管道,并使用$unwind操作数组放松分成几个文件:

原创文件:

结果后 $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} 
]} 

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

我怎样才能AP在另一个操作中将每个文档中的tests密钥的值提升一个级别(即,消除从$unwind创建的重复tests个密钥)以获得以下结果?

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

重复?这与重复项有什么关系?当然,你所要问的只是如何让''tests.status''等进入''status''。那是你问的对吗?只需重新命名密钥。 –

+1

可能重复[是否可以重命名PyMongo中的Mongo查询的输出中的字段?](http://stackoverflow.com/questions/14463087/is-it-possible-rename-fields-in-the-outputs- mongo-query-in-pymongo) –

+0

@BlakesSeven不,这不是重命名,它正在移动'tests'的值并将它合并到父项中。 –

回答

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]); 
     } 
    }); 
+0

谢谢,这将工作,但有没有更通用的方法来做到这一点,而无需投影每一个键?真正的数据(在问题中没有显示)在'tests'散列中有很多键。 –

+0

@KenLiu,也许你可以尝试用'cursor forEach'来做到这一点,就像我在答案中所显示的那样。 – zangw