Dead_Light
Dead_Light

Reputation: 27

How to edit a value inside of a dictionary inside of array in MongoDB?

{
    "_id": 1359185710985371235,
    "main": 2,
    "streamers": [{"name": "me", "count": 1},{"anothername", "count": 0}]
}

hey, I have a problem with mongodb and pymongo so basically i want to edit "count" inside of "streamers" . like i want to change count of "name": "me", "count": 1 to "name": "me", "count": 3How can i do it? Please answer if you know MongoDB and also provide a console command on how to do it.

Upvotes: 0

Views: 298

Answers (2)

prasad_
prasad_

Reputation: 14287

From mongo shell:

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

From Python shell using PyMongo:

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

Upvotes: 1

Belly Buster
Belly Buster

Reputation: 8814

Pymongo way to do it:

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}))

Output:

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

Upvotes: 0

Related Questions