python操作MongoDB

来源:互联网 发布:微信开发框架java 编辑:程序博客网 时间:2024/05/16 10:55
首先安装pymongo
wget -q http://peak.telecommunity.com/dist/ez_setup.py
python ez_setup.py pymongo
 
example:
import pymongoconnection=pymongo.Connection('localhost',27017)db = connection.dbnamecollection = db.dbtabledata = collection.find({'name':'key'})    //collection.find_one() limit 1for i in data:    print i

 
 
sql操作:
>>> 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('...')批量插入
 
>>> 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)
>>> db.collection_names()
[u'posts', u'system.indexes']获取单个文档

>>> 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']}查询多个文档

>> 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'}加条件的查询

>>> posts.find_one({"author": "Mike"})高级查询

>>> posts.find({"date": {"$lt": d}}).sort("author")统计数量

>>> posts.count()
 

3加索引

>>> from pymongo import ASCENDING, DESCENDING
>>> posts.create_index([("date", DESCENDING), ("author", ASCENDING)])
u'date_-1_author_1'查看查询语句的性能

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

示例代码:

创建Connection时,指定host及port参数
>>> import pymongo
>>> conn = pymongo.Connection(host='127.0.0.1',port=27017)

连接数据库
>>> db = conn.ChatRoom

>>> db = conn['ChatRoom']

连接聚集
>>> account = db.Account

>>> account = db["Account"]

查看全部聚集名称
>>> db.collection_names()

查看聚集的一条记录
>>> db.Account.find_one()
>>> db.Account.find_one({"UserName":"keyword"})

查看聚集的字段
>>> db.Account.find_one({},{"UserName":1,"Email":1})
{u'UserName': u'libing', u'_id': ObjectId('4ded95c3b7780a774a099b7c'), u'Email': u'libing@35.cn'}
>>> db.Account.find_one({},{"UserName":1,"Email":1,"_id":0})
{u'UserName': u'libing', u'Email': u'libing@35.cn'}

查看聚集的多条记录
>>> for item in db.Account.find():
item
>>> for item in db.Account.find({"UserName":"libing"}):
item["UserName"]

查看聚集的记录统计
>>> db.Account.find().count()
>>> db.Account.find({"UserName":"keyword"}).count()

聚集查询结果排序
>>> db.Account.find().sort("UserName") --默认为升序
>>> db.Account.find().sort("UserName",pymongo.ASCENDING) --升序
>>> db.Account.find().sort("UserName",pymongo.DESCENDING) --降序

聚集查询结果多列排序
>>> db.Account.find().sort([("UserName",pymongo.ASCENDING),("Email",pymongo.DESCENDING)])


添加记录
>>> db.Account.insert({"AccountID":21,"UserName":"libing"})

修改记录
>>> db.Account.update({"UserName":"libing"},{"$set":{"Email":"libing@126.com","Password":"123"}})

删除记录
>>> db.Account.remove() -- 全部删除
>>> db.Test.remove({"UserName":"keyword"})

 

正则使用
rows = collection.find({'wlj':{'$regex':'10.203.10.\d+'}})

原创粉丝点击