简体   繁体   English

使用PyMongo将事物添加到MongoDB文档中

[英]Adding things into a MongoDB document using PyMongo

Using MongoDB, I have a history collection, with multiple documents in it. 使用MongoDB,我有一个history集合,其中包含多个文档。 When initiatied, they look like this : 启动时,它们如下所示:

{'_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)
    }
 ]
}

Using PyMongo, I would like a query that adds things into a document (for instance, for the document with {'category' : 'blue'} ), in the timeline element, like that : 使用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)
    }
 ]
}

The only thing I found out (with collection.update_one() ) erases the previous content : 我发现的唯一内容(与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)
    }
 ]
}

Thanks 谢谢

Use the update operator $push . 使用更新运算符$ push

db.my_collection.update_one({'category': 'blue'}, {
    '$push': {'timeline': {'score': 30, 'when': datetime.datetime.now()}}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM