使用PyMongo将内容添加到MongoDB文档中
使用MongoDB,我有一个使用PyMongo将内容添加到MongoDB文档中,mongodb,python-3.x,pymongo,Mongodb,Python 3.x,Pymongo,使用MongoDB,我有一个历史集合,其中包含多个文档。刚开始时,它们看起来是这样的: {'_id': ObjectId('58a71211545fc61fd8b2f420'), 'category': 'blue', 'last_update': datetime.datetime(2017, 2, 14, 0, 1), 'timeline': [ { 'score': 0, 'when': datetime.datetime(2017, 2, 14, 0, 1)
历史
集合,其中包含多个文档。刚开始时,它们看起来是这样的:
{'_id': ObjectId('58a71211545fc61fd8b2f420'),
'category': 'blue',
'last_update': datetime.datetime(2017, 2, 14, 0, 1),
'timeline': [
{
'score': 0,
'when': datetime.datetime(2017, 2, 14, 0, 1)
}
]
}
{'_id': ObjectId('58a71211545fc61fd8b2f421'),
'category': 'red',
'last_update': datetime.datetime(2017, 2, 14, 0, 1),
'timeline': [
{
'score': 0,
'when': datetime.datetime(2017, 2, 14, 0, 1)
}
]
}
使用PyMongo,我希望在timeline
元素中有一个将内容添加到文档中的查询(例如,对于带有{'category':'blue'}
)的文档,如下所示:
{'_id': ObjectId('58a71211545fc61fd8b2f420'),
'category': 'blue',
'timeline': [
{
'score': 0,
'when': datetime.datetime(2017, 2, 14, 0, 1)
},
{
'score': 10,
'when': datetime.datetime(2017, 2, 14, 0, 2)
},
{
'score': 20,
'when': datetime.datetime(2017, 2, 14, 0, 3)
}
]
}
我发现的唯一一件事(使用collection.update_one()
)会删除以前的内容:
{'_id': ObjectId('58a71211545fc61fd8b2f420'),
'category': 'blue',
'timeline': [
{
'score': 10,
'when': datetime.datetime(2017, 2, 14, 0, 2)
},
{
'score': 20,
'when': datetime.datetime(2017, 2, 14, 0, 3)
}
]
}
谢谢使用
你能展示一下你是如何使用db.my_collection.update_one({'category':'blue'},{'set':{'timeline':[{'score':30,'when':datetime.datetime.now()}}}你能试一下$push而不是$set吗?push操作符用于数组和字段。就像这样?
db.data_graph\u dev.update_one({'category':'blue'}},{'set':{'timeline':{'push':[{'score':30,'temps':datetime.datetime.now()}]}}}})
=>我得到这个错误:WriteError:美元($)“timeline”中的前缀字段“$push”。$push”对存储无效。
No只需将$set运算符替换为$push。其余保持不变。类似于db.my_collection.update_one({'category':'blue'},{'push':{'timeline':[{'score':30,'when':datetime.datetime.now()}}
db.my_collection.update_one({'category': 'blue'}, {
'$push': {'timeline': {'score': 30, 'when': datetime.datetime.now()}}}