将文档加入在pymongo中共享相同值的集合中

时间:2017-07-24 17:13:18

标签: python pymongo

如何合并共享相同值的集合中的两个文档 - Cycle?

{'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('_______')}

1 个答案:

答案 0 :(得分: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')}

dict不能有两个名称相同的键,而BSON文档不应该有两个同名的键,所以我重命名了两个"时间"字段"时间1"和"时间2"在" $项目"相。