python连接mongodb简明教程


这篇没有找到原出处
import pymongo
con = pymongo.Connection('localhost', 27017)
mydb = con.mydb # new a database
mydb.add_user('test', 'test') # add a user
mydb.authenticate('test', 'test') # check auth
muser = mydb.user # new a table
muser.save({'id':1, 'name':'test'}) # add a record
muser.insert({'id':2, 'name':'hello'}) # add a record
muser.find_one() # find a record
muser.find_one({'id':2}) # find a record by query
muser.create_index('id')
muser.find().sort('id', pymongo.ASCENDING) # DESCENDING
# muser.drop() delete table
muser.find({'id':1}).count() # get records number
muser.find({'id':1}).limit(3).skip(2) # start index is 2 limit 3 records
muser.remove({'id':1}) # delet records where id = 1

muser.update({'id':2}, {'$set':{'name':'haha'}}) # update one recor

======================================================================

下面再贴一些类似非python的api参考:
mongo -path
db.AddUser(username,password) 添加用户
db.auth(usrename,password) 设置数据库连接验证
db.cloneDataBase(fromhost) 从目标服务器克隆一个数据库
db.commandHelp(name) returns the help for the command
db.copyDatabase(fromdb,todb,fromhost) 复制数据库fromdb—源数据库名称,todb—目标数据库名称,fromhost—源数据库服务器地址
db.createCollection(name,{size:3333,capped:333,max:88888}) 创建一个数据集,相当于一个表
db.currentOp() 取消当前库的当前操作
db.dropDataBase() 删除当前数据库
db.eval_r(func,args) run code server-side
db.getCollection(cname) 取得一个数据集合,同用法:db['cname'] or db.cname
db.getCollenctionNames() 取得所有数据集合的名称列表
db.getLastError() 返回最后一个错误的提示消息
db.getLastErrorObj() 返回最后一个错误的对象
db.getMongo() 取得当前服务器的连接对象get the server connection object
db.getMondo().setSlaveOk() allow this connection to read from then nonmaster membr of a replica pair
db.getName() 返回当操作数据库的名称
db.getPrevError() 返回上一个错误对象
db.getProfilingLevel() ?什么等级
db.getReplicationInfo() ?什么信息
db.getSisterDB(name) get the db at the same server as this onew
db.killOp() 停止(杀死)在当前库的当前操作
db.printCollectionStats() 返回当前库的数据集状态
db.printReplicationInfo()
db.printSlaveReplicationInfo()
db.printShardingStatus() 返回当前数据库是否为共享数据库
db.removeUser(username) 删除用户
db.repairDatabase() 修复当前数据库
db.resetError()
db.runCommand(cmdObj) run a database command. if cmdObj is a string, turns it into {cmdObj:1}
db.setProfilingLevel(level) 0=off,1=slow,2=all
db.shutdownServer() 关闭当前服务程序
db.version() 返回当前程序的版本信息
db.linlin.find({id:10}) 返回linlin数据集ID=10的数据集
db.linlin.find({id:10}).count() 返回linlin数据集ID=10的数据总数
db.linlin.find({id:10}).limit(2)返回linlin数据集ID=10的数据集从第二条开始的数据集
db.linlin.find({id:10}).skip(8) 返回linlin数据集ID=10的数据集从0到第八条的数据集
db.linlin.find({id:10}).limit(2).skip(8) 返回linlin数据集ID=1=的数据集从第二条到第八条的数据
db.linlin.find({id:10}).sort() 返回linlin数据集ID=10的排序数据集
db.linlin.findOne([query]) 返回符合条件的一条数据
db.linlin.getDB() 返回此数据集所属的数据库名称
db.linlin.getIndexes() 返回些数据集的索引信息
db.linlin.group({key:…,initial:…,reduce:…[,cond:...]})
db.linlin.mapReduce(mayFunction,reduceFunction,)
db.linlin.remove(query) 在数据集中删除一条数据
db.linlin.renameCollection(newName) 重命名些数据集名称
db.linlin.save(obj) 往数据集中插入一条数据
db.linlin.stats() 返回此数据集的状态
db.linlin.storageSize() 返回此数据集的存储大小
db.linlin.totalIndexSize() 返回此数据集的索引文件大小
db.linlin.totalSize() 返回些数据集的总大小
db.linlin.update(query,object[,upsert_bool])在此数据集中更新一条数据
db.linlin.validate() 验证此数据集
db.linlin.getShardVersion() 返回数据集共享版本号
db.linlin.find({‘name’:'foobar’}) select * from linlin where name=’foobar’
db.linlin.find() select * from linlin
db.linlin.find({‘ID’:10}).count() select count(*) from linlin where ID=10
db.linlin.find().skip(10).limit(20) 从查询结果的第十条开始读20条数据 select * from linlin limit 10,20 ———-mysql
db.linlin.find({‘ID’:{$in:[25,35,45]}}) select * from linlin where ID in (25,35,45)
db.linlin.find().sort({‘ID’:-1}) select * from linlin order by ID desc
db.linlin.distinct(‘name’,{‘ID’:{$lt:20}}) select distinct(name) from linlin where ID<20
db.linlin.group({key:{'name':true},cond:{'name':'foo'},reduce:function(obj,prev){prev.msum+=obj.marks;},initial:{msum:0}})
select name,sum(marks) from linlin group by name
db.linlin.find('this.ID<20′,{name:1}) select name from linlin where ID<20
db.linlin.insert({'name':'foobar’,'age':25}) insert into linlin ('name','age’)values('foobar',25)
db.linlin.insert({'name':'foobar’,'age':25,’email’:'cclove2@163.com’})
db.linlin.remove({}) delete * from linlin
db.linlin.remove({'age':20}) delete linlin where age=20
db.linlin.remove({'age':{$lt:20}}) delete linlin where age<20
db.linlin.remove({'age':{$lte:20}}) delete linlin where age<=20
db.linlin.remove({'age':{$gt:20}}) delete linlin where age>20
db.linlin.remove({‘age’:{$gte:20}}) delete linlin where age>=20
db.linlin.remove({‘age’:{$ne:20}}) delete linlin where age!=20
db.linlin.update({‘name’:'foobar’},{‘$set’:{‘age’:36}}) update linlin set age=36 where name=’foobar’
db.linlin.update({‘name’:'foobar’},{‘$inc’:{‘age’:3}}) update linlin set age=age+3 where name=’foobar’



下面这篇转自http://blog.nosqlfan.com/html/2989.html

文是一个Python 使用MongoDB的简单教程,将使用pymongo对MongoDB进行的各种操作进行了简单的汇总,我们进行了简单整理,使用Python的同学可以看一看。

下载相应平台的版本,解压即可。为方便使用,将bin路径添加到系统path环境变量里。其中mongod是服务器,mongo是客户shell,然后创建数据文件目录:在c盘下创建data文件夹,里面创建db文件夹。

基本使用:

安装对应语言的Driver,Python 安装 pymongo

?
1
$ easy_install pymongo

使用方法总结,摘自官方教程

创建连接

?
1
2
>>> import pymongo
>>> connection=pymongo.Connection('localhost',27017)

切换数据库

?
1
>>> db = connection.test_database

获取collection

?
1
>>> collection = db.test_collection

db和collection都是延时创建的,在添加Document时才真正创建

文档添加,_id自动创建

?
1
2
3
4
5
6
7
8
>>> import datetime
>>> post = {"author": "Mike",
...         "text": "My first blog post!",
...         "tags": ["mongodb", "python", "pymongo"],
...         "date": datetime.datetime.utcnow()}
>>> posts = db.posts
>>> posts.insert(post)
ObjectId('...')

批量插入

?
1
2
3
4
5
6
7
8
9
10
>>> new_posts = [{"author": "Mike",
...               "text": "Another post!",
...               "tags": ["bulk", "insert"],
...               "date": datetime.datetime(2009, 11, 12, 11, 14)},
...              {"author": "Eliot",
...               "title": "MongoDB is fun",
...               "text": "and pretty easy too!",
...               "date": datetime.datetime(2009, 11, 10, 10, 45)}]
>>> posts.insert(new_posts)
[ObjectId('...'), ObjectId('...')]

获取所有collection(相当于SQL的show tables)

?
1
2
>>> db.collection_names()
[u'posts', u'system.indexes']

获取单个文档

?
1
2
>>> posts.find_one()
{u'date': datetime.datetime(...), u'text': u'My first blog post!', u'_id': ObjectId('...'), u'author': u'Mike', u'tags': [u'mongodb', u'python', u'pymongo']}

查询多个文档

?
1
2
3
4
5
6
>> for post in posts.find():
...   post
...
{u'date': datetime.datetime(...), u'text': u'My first blog post!', u'_id': ObjectId('...'), u'author': u'Mike', u'tags': [u'mongodb', u'python', u'pymongo']}
{u'date': datetime.datetime(2009, 11, 12, 11, 14), u'text': u'Another post!', u'_id': ObjectId('...'), u'author': u'Mike', u'tags': [u'bulk', u'insert']}
{u'date': datetime.datetime(2009, 11, 10, 10, 45), u'text': u'and pretty easy too!', u'_id': ObjectId('...'), u'author': u'Eliot', u'title': u'MongoDB is fun'}

加条件的查询

?
1
>>> posts.find_one({"author": "Mike"})

高级查询

?
1
>>> posts.find({"date": {"$lt": d}}).sort("author")

统计数量

?
1
2
>>> posts.count()
3

加索引

?
1
2
3
>>> from pymongo import ASCENDING, DESCENDING
>>> posts.create_index([("date", DESCENDING), ("author", ASCENDING)])
u'date_-1_author_1'

查看查询语句的性能

?
1
2
3
4
>>> posts.find({"date": {"$lt": d}}).sort("author").explain()["cursor"]
u'BtreeCursor date_-1_author_1'
>>> posts.find({"date": {"$lt": d}}).sort("author").explain()["nscanned"]
2

附自己总结的一点小心得,仅供参考

缺点

  • 不是全盘取代传统数据库(NoSQLFan:是否能取代需要看应用场景)
  • 不支持复杂事务(NoSQLFan:MongoDB只支持对单个文档的原子操作)
  • 文档中的整个树,不易搜索,4MB限制?(NoSQLFan:1.8版本已经修改为16M)

特点(NoSQLFan:作者在这里列举的很多只是一些表层的特点):

  • 文档型数据库,表结构可以内嵌
  • 没有模式,避免空字段开销(Schema Free)
  • 分布式支持
  • 查询支持正则
  • 动态扩展架构
  • 32位的版本最多只能存储2.5GB的数据(NoSQLFan:最大文件尺寸为2G,生产环境推荐64位)

名词对应

  • 一个数据项叫做 Document(NoSQLFan:对应MySQL中的单条记录)
  • 一个文档嵌入另一个文档(comment 嵌入 post)叫做 Embed
  • 储存一系列文档的地方叫做 Collections(NoSQLFan:对应MySQL中的表)
  • 表间关联,叫做 Reference

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值