使用python语言操作MongoDB

21 篇文章 0 订阅
1 篇文章 0 订阅

本文转载自:http://blog.csdn.net/xsj_blog/article/details/52032969

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"})  

   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56

实例如下:

#-*-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'操作数据库完成!'
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值