使用python语言操作MongoDB

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


pymongo的两种安装命令

pip install pymongo

easy_install pymongo

Python操作MongoDB

#encoding:utf=8  
import pymongo  

connection=pymongo.Connection('10.32.38.50',27017)  

#选择myblog库  
db=connection.myblog  

# 使用users集合  
collection=db.users  




#添加命令如下:  

# 添加单条数据到集合中  
user = {"name":"xiaoxu","age":"23"}  
collection.insert(user)     #添加数据
collection.save(users)      #添加数据

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




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


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


#查询命令如下: 

#查询单条记录  
print collection.find_one()  

#查询所有记录  
for data in collection.find():  
    print data  

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

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

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

实例如下:

#-*-coding:utf8-*-
import pymongo

connection = pymongo.MongoClient()
tdb = connection.Jikexueyuan
post_info = tdb.test

jike = {'name':u'极客', 'age':'5', 'skill': 'Python'}
god = {'name': u'玉皇大帝', 'age': 36000, 'skill': 'creatanything', 'other': u'王母娘娘不是他的老婆'}
godslaver = {'name': u'月老', 'age': 'unknown', 'other': u'他的老婆叫孟婆'}
post_info.insert(jike)
post_info.insert(god)
post_info.insert(godslaver)
post_info.remove({'name': u'极客'})

print u'操作数据库完成!'
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值