2016-12-07 107 views
0

名爲groups的集合的每個實例都有一個名爲actives的字段,它是「子文檔」的列表,即形式爲{鍵:值}的東西。子文檔的一個字段(鍵)是id_,它是一個字符串。Pymongo查詢「子文檔」

如果我參加該組存在於groups所有實例所有子文檔,那麼不會有2個相等id_,即id_唯一地標識每個子文檔。但是,我得到一個新的子文檔。我需要運行一個帶有子文檔ID的程序,該程序會去一個網站並提取有關子文檔的信息。在這個信息中,我找到了該子文檔所屬的組。但是,如果我已經有了一些子文檔,在groups的與「新」子文檔相同的情況下,我不想運行此程序。

如何列出所有文檔(或groups的實例)的所有子文檔的ID?

編輯:

假設DB組的文件是:

doc1: {"neighbourhood": "n1", "actives": [{"id_": "MHTEQ", "info": "a_long_string"}, {"id_": "PNPQA", "info": "a_long_string"}]} 

doc2: {"neighbourhood": "n2", "actives": [{"id_": "MERVX", "info": "a_long_string"}, {"id_": "ZDKJW", "info": "a_long_string"}]} 

我想要做的是列出所有的"id_",即

def list_ids(groups): 
    do_sth_with_groups 
    return a_list 

print(list_ids(groups)) 

output: ["MHTEQ", "PNPQA", "MERVX", "ZDKJW"] 
+3

你提的問題是很難不樣本文件和預期輸出理解。請考慮提供更多信息。 – styvane

+0

@Styvane我編輯了我的問題。不便之處,敬請原諒。 –

回答

1

使用聚合管道與$unwind$project運營商。

results = db['collection'].aggregate(
    [ 
    {"$project": {"actives": 1, "_id": 0}}, 
    {"$unwind": "$actives"}, 
    {"$project": {"id_str": "$actives.id_", "_id": 0}} 
    ] 
) 
return list(results) 

https://docs.mongodb.com/v3.2/reference/operator/aggregation/unwind/ https://docs.mongodb.com/v3.2/reference/operator/aggregation/project/

樣本輸出

{ 
    "id_str" : "MHTEQ" 
} 
{ 
    "id_str" : "PNPQA" 
} 
{ 
    "id_str" : "MERVX" 
} 
{ 
    "id_str" : "ZDKJW" 
}