python调用mongodb
官方文档:
http://api.mongodb.org/python/current/tutorial.html
安装
sudo pip install pymongo
测试Python驱动
启动ipython:
import pymongo
client=pymongo.MongoClient("127.0.0.1", 27017)
#Getting a Database¶
db=client.test_database
#Getting a Collection
collection = db.test_collection
post={"name":"xwp1", "age":32}
#Inserting a Document
post_id = collection.insert_one(post).inserted_id
db.collection_names()
post={"name":"xwp2", "age":33}
post_id = collection.insert_one(post).inserted_id
collection.find_one()
for cur in collection.find():
print cur
cur=collection.find()
cur.next()
cur.next()
cur.next()
print collection.count()
collection.find({"name":"xwp"}).count()
collection.find({"name":"xwp1"}).count()
Aggregation Examples
首先,插入一些数据进行聚合:
db = client.aggregation_example
result = db.things.insert_many([
{"x":1,"tags":["dog","cat"]},
{"x":2,"tags":["cat"]},
{"x":2,"tags":["mouse","cat","dog"]},
{"x":3,"tags":[]}
])
result.inserted_ids
[ObjectId('...'), ObjectId('...'), ObjectId('...'), ObjectId('...')]
Python字典不含有排序语法,需要使用的SON:
from bson.son import SON
pipeline = [
{"$unwind": "$tags"},
{"$group": {"_id": "$tags", "count": {"$sum": 1}}},
{"$sort": SON([("count", -1), ("_id", -1)])}
]
list(db.things.aggregate(pipeline))
[{u'count': 3, u'_id': u'cat'}, {u'count': 2, u'_id': u'dog'}, {u'count': 1, u'_id': u'mouse'}]
可以使用command()
方法 运行一个聚合explain方法:
db.command('aggregate', 'things', pipeline=pipeline, explain=True)
{u'ok': 1.0,
u'stages': [{u'$cursor': {u'fields': {u'_id': 0, u'tags': 1},
u'query': {},
u'queryPlanner': {u'indexFilterSet': False,
u'namespace': u'aggregation_example.things',
u'parsedQuery': {u'$and': []},
u'plannerVersion': 1,
u'rejectedPlans': [],
u'winningPlan': {u'direction': u'forward',
u'filter': {u'$and': []},
u'stage': u'COLLSCAN'}}}},
{u'$unwind': {u'path': u'$tags'}},
{u'$group': {u'_id': u'$tags', u'count': {u'$sum': {u'$const': 1}}}},
{u'$sort': {u'sortKey': {u'_id': -1, u'count': -1}}}],
u'waitedMS': 0L}
执行 explain=False
db.command('aggregate', 'things', pipeline=pipeline, explain=False)
{u'ok': 1.0,
u'result': [{u'_id': u'cat', u'count': 3},
{u'_id': u'dog', u'count': 2},
{u'_id': u'mouse', u'count': 1}],
u'waitedMS': 0L}