Python3学习(二十一):python操作MongoDB

MongoDB是一个跨平台的NoSQL,基于Key-Value形式保存数据。其储存格式非常类似于Python的字典,因此用Python操作MongoDB会非常的容易。

对Mongo简单的操作代码如下:

#encoding:utf=8  
import pymongo  

conn = pymongo.Connection('************', xxxx) #里面是服务器ip及端口号  

#选择liao库,没有就会自动创建 
db = conn.liao

#使用aoteman集合  
my_set = db['aoteman']

####添加命令如下:  
# 添加单条数据到集合中  
user = {"name":"xiaoxu","age":"23"}  
my_set.insert(user)     #添加数据

#同时添加多条数据到集合中  
users=[{"name":"xiaoxu","age":"23"},{"name":"xiaoli","age":"20"}]  
my_set.insert(users)    #添加数据

####删除命令如下:
my_set.remove({"name":"xiaoxu"})

####修改命令如下:
my_set.update(xxxx)

####查询命令如下: 
#查询单条记录  
print(my_set.find_one())  

#查询所有记录  
for i in my_set.find():  
    print(i)  

#查询此集合中数据条数  
print(my_set.count())  

#简单参数查询  
for i in my_set.find({"name":"1"}):  
    print(i)  

#使用find_one获取一条记录  
print(my_set.find_one({"name":"1"}))

猜你喜欢

转载自blog.csdn.net/liao392781/article/details/80776434