1

I have connected one mongo db using below connections and I am trying to insert one record/row/document in that db using post method but I am so confused how to do that by below scenario.

"By post method check if the record already present or not if not then create a record"

This is how I made connection and connection successfully made. the fields in dcollection are id, firstname, lastname, student_id

I want to do this.

"By post method check if the record already present or not if not then create a record".

import pymongo
from pymongo import MongoClient
db_name = 'student_db'
client = MongoClient('localhost', 27017)
db_obj = client[db_name]
collection=db_obj['mongo_app_student']
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

1 Answers1

1

Mongo has an awesome set of upsert commands like replace_one, replace_many

see another great post about it and, of course, -> mongo docs

see below example, hope this is what you're looking for

client = MongoClient('localhost', 27017)
db = client.student_db
collection = db.mongo_app_student
collection.insert_one({"name":"vladimir"})
for document in collection.find(): 
    pprint(document)

Merge command

obj1 = {"name":"Vladimir"} # V in upper case here
collection.update_one( { "name" : obj1["name"] } , {"$set":obj1} , True ) # True means Upsert

obj2 = {"name":"Being Human"}
collection.update_one( { "name" : obj2["name"] } , {"$set":obj2} , True ) # True means Upsert
for document in collection.find(): 
    pprint(document)

another example from pymongo docs

obj1 = {"name":"Vladimir"}
obj2 = {"name":"Being Human"}
requests = [ReplaceOne({"name" : obj1["name"]}, obj1, upsert=True),ReplaceOne({"name" : obj2["name"]}, obj2, upsert=True)]
result = collection.bulk_write(requests)
result.modified_count
Vladimir Semashkin
  • 1,270
  • 1
  • 10
  • 21