PyMongo的使用方法详解!最全面的教程
MongoDB操作数据库:# -*- coding=utf-8 -*-#引入Mongo模块 ↓import pymongo#连接数据库服务器 ↓client = pymongo.MongoClient("localhost",27017)#选择数据库 ↓db_test = client.test #推荐使用:db_test = client["test"]#获取集合 ↓collection1 =
·
MongoDB
操作数据库:
# -*- coding=utf-8 -*-
#引入Mongo模块 ↓
import pymongo
#连接数据库服务器 ↓
client = pymongo.MongoClient("localhost",27017)
#选择数据库 ↓
db_test = client.test #推荐使用:db_test = client["test"]
#获取集合 ↓
collection1 = db_test.col
#获取collection1集合内全部数据 ↓
x = collection1.find()
for i in x:
print(i)#打印一条数据
print(i["name"])#打印key=name的value值
print(type(i))#字典
break
新增文档:
# -*- coding=utf-8 -*-
import pymongo
client = pymongo.Mongoclient("localhost",27017)
db = client["itsource"]
#1)新增一条数据 insert_one()
db.admin.insert_one({"name":"李智恩","age":25}})
#2)新增多条数据 insert_many()
db.admin.insert_many([{"name":"李智恩"},{"name":"IU"}])
查找文档:
# -*- coding=utf-8 -*-
import pymongo
client = pymongo.MongoClient("localhost",27017)
db = client["itsource"]
collection1 = db["admin"]
#1)读取一条数据 find_one()
x = collection1.find_one()
print(x)
输出:
{'_id': ObjectId('5e2fb3dbb5b77d6f312727ad'), 'name': '张三', 'age': 19.0, 'address': 'changsha', 'height': 185.0}
#2)读取多条数据:
c = collection1.find() #返回一个游标,需要遍历获取所有数据
for i in c:
print(i)
#3)条件查询
c = collection1.find({"name":"李智恩"}) #返回一个游标,需要遍历获取所有数据
for i in c:
print(i)
修改文档:
语法:
collection1.update_one( {“key”:“value”}, {"$set":{"修改目标":""}} )
# -*- coding=utf-8 -*-
import pymongo
client = pymongo.MongoClient("localhost",27017)
db = client["itsource"]
collection1 = db["admin"]
collection1.update_one({"name":"李知恩"},{"$set":{"age":23}})
删除数据:
语法:
collection1.delete_one({})
更多推荐
已为社区贡献1条内容
所有评论(0)