【问题标题】:How to edit a value inside of a dictionary inside of array in MongoDB?如何在 MongoDB 中的数组内编辑字典内的值?
【发布时间】:2020-04-10 08:41:49
【问题描述】:
{
    "_id": 1359185710985371235,
    "main": 2,
    "streamers": [{"name": "me", "count": 1},{"anothername", "count": 0}]
}

嘿,我对 mongodb 和 pymongo 有疑问,所以基本上我想在 "count" 内部编辑 "streamers" 。就像我想将"name": "me", "count": 1 的计数更改为"name": "me", "count": 3我该怎么做? 如果您了解 MongoDB,请回答,并提供有关如何操作的控制台命令。

【问题讨论】:

  • 如何在数组中找到要更新的文档?按名字?你想更新数组中的一个文档,还是可以有多个?

标签: python arrays database mongodb pymongo


【解决方案1】:

来自mongo壳:

db.example.insertOne(
{
    "_id": NumberLong("1359185710985371235"),
    "main": 2,
    "streamers": [ { "name": "me", "count": 1 },{ name: "anothername", "count": 0 } ]
} )

db.example.updateOne( 
  { _id: NumberLong("1359185710985371235"), 'streamers.name': 'me' },
  { $set: { 'streamers.$[st].count' : 3 } }, 
  { arrayFilters: [ { 'st.name': 'me'  } ] } 
)

使用 PyMongo 从 Python shell:

db.example.update_one( 
  { '_id': 1359185710985371235, 'streamers.name': 'me' }, 
  { '$set': { 'streamers.$[st].count' : 3 } }, 
  array_filters = [ { 'st.name': 'me'  } ] 
)

【讨论】:

    【解决方案2】:

    Pymongo 方法:

    import pymongo
    
    db = pymongo.MongoClient()['mydatabase']
    # Data setup
    db.mycollection.insert_one({"main": 2, "streamers": [{"name": "me", "count": 1},{"name": "anothername", "count": 0}]})
    
    record = db.mycollection.find_one({"main": 2})
    streamers = record.get('streamers')
    
    for index, streamer in enumerate(streamers):
        name = streamer.get('name')
    
        if name == "me":
            streamer['count'] = 3
            streamers[index] = streamer
    
    record = db.mycollection.update_one({"_id": record['_id']}, {'$set': {'streamers': streamers}})
    
    print(db.mycollection.find_one({"main": 2}))
    

    输出:

    {'_id': ObjectId('5e904277152eaccd43dddf8d'), 'main': 2, 'streamers': [{'name': 'me', 'count': 3}, {'name': 'anothername', 'count': 0}]}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-24
      • 1970-01-01
      • 1970-01-01
      • 2021-10-06
      • 2019-04-17
      • 1970-01-01
      • 2020-08-21
      • 1970-01-01
      相关资源
      最近更新 更多