文章来源于网络收集而来,版权归原创者所有,如有侵权请及时联系!
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}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论