操作步骤:
1. 连接数据库,生成数据库连接对象
conn = pymongo.MongoClient(‘localhost‘,27017)
2. 选择要操作的数据库,生成数据库对象 (__setitem__)
db = conn.stu
db = conn[‘stu‘]
3. 获取集合对象
myset = db.class
myset = db[‘class‘]
4. 通过集合对象调用mongodb数据库操作函数
增删改查,聚合,索引。。。。。
5. 关闭数据库连接
conn.close()
————————————————————————————————————–
插入文档:
myset.insert() 插入数据 功能同 mongoshell
myset.insert_many() 插入多条
myset.insert_one() 插入一条
myset.save() 插入数据,通过_id可以修改
—————————————————————————————————————-
查找操作:
myset.find()
功能 : 对数据库进行查找
参数 : 同mongoshell find()
返回值 : 返回游标对象 #返回是一个对象,因此可以进行for循环
myset.find_one() 用法同mongoshell中 findOne()
返回一个字典
由于myset.find()返回的是一个对象,因此含有next(),limit(),skip(),count()这几个方法。
但用着几个方法也是有限制的,如果之前用过了for循环的话,就不能在用这几个方法了
———————————————————————————————————————
修改操作:
update(query,update,upsert = False,multi = False)
update_many()
update_one()
——————————————————————————————————————–
删除操作:
remove(query,multi = True)
功能: 删除文档
参数: query 筛选条件
multi 默认True表示删除所有符合条件的,False只删除一条
———————————————————————————————————————-
复合操作
查找King = 船长,并删除
print(myset.find_one_and_delete({“King”:”船长”}))
frompymongo import MongoClient
#创建数据库连接对象
conn= MongoClient(“localhost”, 27017)
#创建数据库对象
db=conn.stu
#db= conn[“stu”]
#创建集合对象
myset=db.class4
#数据操作
#print(dir(myset)) #查看对象方法
#添加
myset.insert({“name”:”路飞”,”Role”:”船长”})
myset.insert([{“name”:”山治”,”Role”:”厨师”},{“name”:”罗”,”Role”:”船长”}])
myset.insert_many([{“name”:”娜美”,”Role”:”掌舵手”},{“name”:”大妈”,”Role”:”四皇”}])
myset.insert_one({“name”:”香克斯”,”Role”:”四皇”})
myset.save({“_id”:1,”name”:”黑胡子”,”Role”:”船长”})
myset.save({“_id”:1,”name”:”白胡子”,”Role”:”船长”})
#查找
cursor= myset.find({“Role”:{“$eq”:”四皇”}},{“_id”:0})
print(cursor)for i incursor:
print(i[“name”],”—-“,i[“Role”])
dic=myset.find_one()
print(dic)
#获取下一条数据
print(cursor.next())
print(cursor.next())
#显示第2条数据for i in cursor.skip(1).limit(1):
print(i)
#排序for i in cursor.sort([(“name”,-1)]):
print(i)
query={“$or”:[{“sex”:”w”},{“age”:{“$lt”:”18″}}]}
cursor= myset.find(query ,{“_id”:0})for i incursor:
print(i)
#修改操作
myset.update({“name”:”zengsf”},{“$unset”:{“sex”:””}})
#同时修改多条文档
myset.update({“name”:”zengsf”},{“$set”:{“age”:”21″}},multi =True)
#如果匹配文档不存在则插入
myset.update({“name”:”骷髅”},{“$set”:{“King”:”武士”}},upsert =True)
#删除
myset.remove({“name”:”黑胡子”})
#复合操作
#查找King=船长,并删除
print(myset.find_one_and_delete({“Role”:”船长”}))
#关闭连接
conn.close()
索引操作:
ensure_index() 创建索引
list_indexes() 查看索引
drop_index() 删除一个索引
drop_indexes() 删除所有索引
#创建一个正向索引
index = myset.ensure_index(“name”)#创建一个逆向索引
index = myset.ensure_index([(“age”,-1)])print(index)#获取当前集合中的索引
for i inmyset.list_indexes():print(i)#删除所有索引
myset.drop_indexes()#删除单个索引
myset.drop_index(“age_-1”)#其它索引类型#创建复合索引
myset.ensure_index([(“name”,1),(“age”,1)])#创建唯一索引
myset.ensure_index(“name”,name = “MyIndex”,unique =True)#创建稀疏索引
myset.ensure_index(“age”,sparse = True)
——————————————————————————————————————–
聚合操作
aggregate([])
参数和mongoshell一样
返回值和find()函数一样也是得到一个游标对象