【问题标题】:Adding things into a MongoDB document using PyMongo使用 PyMongo 将内容添加到 MongoDB 文档中
【发布时间】:2017-07-08 03:27:03
【问题描述】:

使用 MongoDB,我有一个 history 集合,其中包含多个文档。启动时,它们看起来像这样:

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

谢谢

【问题讨论】:

  • 你能说明你是如何使用update_one的吗?
  • db.my_collection.update_one({'category': 'blue'},{'$set': {'timeline' : [{ 'score' : 30, 'when': datetime.datetime.now() }]}}
  • 你可以试试 $push 代替 $set 吗?数组的推送操作符和字段的设置。
  • 喜欢吗? db.data_graph_dev.update_one({'category': 'blue'}, {'$set': {'timeline' : {'$push' : [{ 'score' : 30, 'temps': datetime.datetime.now() }]}}}) => I get this error : WriteError: The dollar ($) prefixed field '$push' in 'timeline.$push' is not valid for storage.
  • 不只是将 $set 运算符替换为 $push。休息保持不变。类似db.my_collection.update_one({'category': 'blue'},{'$push': {'timeline' : [{ 'score' : 30, 'when': datetime.datetime.now() }]}}

标签: mongodb python-3.x pymongo


【解决方案1】:

使用the update operator $push

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

【讨论】:

    猜你喜欢
    • 2013-01-14
    • 1970-01-01
    • 2015-09-27
    • 1970-01-01
    • 2014-08-01
    • 2019-02-27
    • 2019-08-31
    • 2015-12-21
    • 2014-05-28
    相关资源
    最近更新 更多