Home > database >  How to update row in mongodp in python
How to update row in mongodp in python

Time:02-21

I have a following problem. I am creating a a mongodb. Rows looks like this:

{'_id': ObjectId('62136674d12e4f7384caf6c0'), 'visit_id': 595002379, 'referal': '', 'pageviews': [], 'ab_variants': [{'id': 1, 'var': 0}]}.

I am inserting new rows. I want to check if visit_id already exists. If yes, I want to extend ab_variants for example like this:

{'_id': ObjectId('62136674d12e4f7384caf6c0'), 'visit_id': 595002379, 'referal': '', 'pageviews': [], 'ab_variants': [{'id': 1, 'var': 0}, {'id': 2, 'var': 1}]}.

What I tried co far:

from pymongo import MongoClient

try:
    conn = MongoClient()
    print("Connected successfully!!!")
except:
    print("Could not connect to MongoDB")


# database
db = conn.database

# Created or Switched to collection names: my_gfg_collection
collection = db.my_gfg_collection

# drop
db.my_gfg_collection.drop()
print("Old data dropped successfully!")

if collection.find_one({"visit_id": 595002379}) is None:
   emp_rec = {
               "visit_id": 595002379),
               "referal": "",
               "pageviews": [],
               "ab_variants": [{"id" : 1),
                                "var" : 0) }]
                        }

else:
   # I WANT TO UPDATE HERE

# Insert Data
rec_id = collection.insert_one(emp_rec)

How can I do this, please?

CodePudding user response:

You can do something like this here

from pymongo import MongoClient

try:
    conn = MongoClient()
    print("Connected successfully!!!")
except:
    print("Could not connect to MongoDB")


# database
db = conn.database

# Created or Switched to collection names: my_gfg_collection
collection = db.my_gfg_collection

# drop
db.my_gfg_collection.drop()
print("Old data dropped successfully!")

# store the document in a variable, if present
record = collection.find_one({"visit_id": 595002379})

if record is None:
   emp_rec = {
               "visit_id": 595002379),
               "referal": "",
               "pageviews": [],
               "ab_variants": [{"id" : 1),
                                "var" : 0) }]
                        }
    # Insert Data
    rec_id = collection.insert_one(emp_rec)
else:
    # I WANT TO UPDATE HERE
    if 'ab_variants' not in record:
        record['ab_variants'] = []
    record['ab_variants'].append(Record that you want to update inside the ab_variants list)
    # update the document
    collection.update({'_id': record['_id']}, {"$set": record}, upsert=True)) 
  • Related