先决条件: MongoDB Python基础知识 我们首先要了解如何在数据库集合中插入文档/条目。然后,我们将研究如何使用python中的pymongo库更新MongoDB中的现有文档。update命令帮助我们更新已经插入MongoDB数据库集合中的查询数据。
null
插入数据
我们首先在MongoDB中插入数据。
- 第一步——建立联系 :端口号默认值:27017
conn = MongoClient(‘localhost’, port-number)
如果使用默认端口号,即27017。备用连接方法:
conn = MongoClient()
- 第2步-创建数据库或切换到现有数据库:
db = conn.dabasename
创建集合或切换到现有集合:
collection = db.collection_name
- 第3步-插入: 要插入数据,请创建dictionary对象并在数据库中插入数据。用于插入数据的方法:
insert_one() or insert_many()
插入后,我们使用find()命令查找集合中的文档。find()方法发出查询以从MongoDB中的集合检索数据。MongoDB中的所有查询都具有单个集合的范围。 注意:数据库集合中的每个条目的ObjectId都不同。 让我们通过代码帮助了解数据插入:-
# Python code to illustrate
# inserting data in MongoDB
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
emp_rec1
=
{
"name"
:
"Mr.Geek"
,
"eid"
:
24
,
"location"
:
"delhi"
}
emp_rec2
=
{
"name"
:
"Mr.Shaurya"
,
"eid"
:
14
,
"location"
:
"delhi"
}
# Insert Data
rec_id1
=
collection.insert_one(emp_rec1)
rec_id2
=
collection.insert_one(emp_rec2)
print
(
"Data inserted with record ids"
,rec_id1,
" "
,rec_id2)
# Printing the data inserted
cursor
=
collection.find()
for
record
in
cursor:
print
(record)
输出:
Connected successfully!!! Data inserted with record ids {'_id': ObjectId('5a02227b37b8552becf5ed2a'), 'name': 'Mr.Geek', 'eid': 24, 'location': 'delhi'} {'_id': ObjectId('5a02227c37b8552becf5ed2b'), 'name': 'Mr.Shaurya', 'eid': 14, 'location': 'delhi'}
更新MongoD中的数据 B
使用的方法:update_one()和update_many() 传递的参数: +筛选文档以匹配要更新的文档 +用于指定要执行的修改的更新文档 +可选的upsert参数
在MongoDB中插入数据后,让我们更新id为24的员工的数据
# Python code to illustrate # updating data in MongoDB # with Data of employee with id:24 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 # update all the employee data whose eid is 24 result = collection.update_many( { "eid" : 24 }, { "$set" :{ "name" : "Mr.Geeksforgeeks" }, "$currentDate" :{ "lastModified" : True } } ) print ( "Data updated with id" ,result) # Print the new record cursor = collection.find() for record in cursor: print (record) |
输出:
Connected successfully!!! Data updated with id {'_id': ObjectId('5a02227b37b8552becf5ed2a'), 'name': 'Mr.Geeksforgeeks', 'eid': 24, 'location': 'delhi', 'lastModified': datetime.datetime(2017, 11, 7, 21, 19, 9, 698000)} {'_id': ObjectId('5a02227c37b8552becf5ed2b'), 'name': 'Mr.Shaurya', 'eid': 14, 'location': 'delhi'}
要查找集合中更新的文档或条目的数量,请使用。
print(result.matched_count)
这里的输出是1。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END