2017-07-24 64 views
1

如何合併共享相同值的集合中的兩個文檔 - 循環?在pymongo中共享相同值的集合中加入文檔

{'Time': datetime.datetime(2015, 5, 25, 9, 4, 39), 
'Cycle': 3796, 
'Explanation': 'A 00146 - Q plastification time', 
'_id': ObjectId('5976272b4a20d138cce55aa3')} 

{'A [s]': 0.0, 
'B [s]': 0.81, 
'C [s]': 3.0, 
'Time': datetime.datetime(2015, 5, 26, 10, 33, 10), 
'PauseTime Z [s]': 0.01, 
'Cycle': 3796, 
'_id': ObjectId('597627244a20d138cce5197a')} 

因此,它看起來像:

{'Time': datetime.datetime(2015, 5, 25, 9, 4, 39), 
'Cycle': 3796, 
'Explanation': 'A 00146 - Q plastification time', 
'A [s]': 0.0, 
'B [s]': 0.81, 
'C [s]': 3.0, 
'Time': datetime.datetime(2015, 5, 26, 10, 33, 10), 
'PauseTime Z [s]': 0.01, 
'_id': ObjectId('_______')} 
+0

這個例子是不可能的,因爲文檔是作爲字典來處理的,字典不能將單個鍵映射到兩個不同的值(例如Time,這可能與mongoDB核心中的假設相同,而不僅僅是python的界面pymongo)。 – sascha

回答

1

如果你表現出的頭文件是一個名爲「C1」集合中,第二個是一個集合稱爲「c2」,您可以使用MongoDB匯聚運算符「$ lookup」加入它們:

for doc in db.c2.aggregate([{ 
    '$lookup': { 
     'from': 'c1', 
     'localField': 'Cycle', 
     'foreignField': 'Cycle', 
     'as': 'joined' 
    } 
}, { 
    '$project': { 
     'Time1': '$Time', 
     'Cycle': '$Cycle', 
     'Explanation': '$joined.Explanation', 
     'Time2': '$joined.Time', 
     'A [s]': '$A [s]', 
     'B [s]': '$B [s]', 
     'C [s]': '$C [s]', 
     'PauseTime Z [s]': '$PauseTime Z [s]' 

    } 
}]): 
    pprint.pprint(doc) 

此輸出:

{u'A [s]': 0.0, 
u'B [s]': 0.81, 
u'C [s]': 3.0, 
u'Cycle': 3796, 
u'Explanation': [u'A 00146 - Q plastification time'], 
u'PauseTime Z [s]': 0.01, 
u'Time1': datetime.datetime(2015, 5, 26, 10, 33, 10), 
u'Time2': [datetime.datetime(2015, 5, 25, 9, 4, 39)], 
u'_id': ObjectId('597627244a20d138cce5197a')} 

的字典不能有兩個鍵具有相同的名稱,以及文件BSON應該有兩個名稱相同的鑰匙,所以我改名爲兩個「$ project」階段中的「Time」字段爲「Time1」和「Time2」。