python调用mongodb

官方文档:

http://api.mongodb.org/python/current/tutorial.html

安装

  1. sudo pip install pymongo

测试Python驱动

启动ipython:

import pymongoclient=pymongo.MongoClient("127.0.0.1", 27017)#Getting a Database¶db=client.test_database#Getting a Collectioncollection = db.test_collectionpost={"name":"xwp1", "age":32}#Inserting a Documentpost_id = collection.insert_one(post).inserted_iddb.collection_names()post={"name":"xwp2", "age":33}post_id = collection.insert_one(post).inserted_idcollection.find_one()for cur in collection.find(): print curcur=collection.find()cur.next()cur.next()cur.next()print collection.count()collection.find({"name":"xwp"}).count()collection.find({"name":"xwp1"}).count()

Aggregation Examples

首先,插入一些数据进行聚合:

  1. db = client.aggregation_example
  2. result = db.things.insert_many([
  3. {"x":1,"tags":["dog","cat"]},
  4. {"x":2,"tags":["cat"]},
  5. {"x":2,"tags":["mouse","cat","dog"]},
  6. {"x":3,"tags":[]}
  7. ])
  8. result.inserted_ids
  9. [ObjectId('...'), ObjectId('...'), ObjectId('...'), ObjectId('...')]

Python字典不含有排序语法,需要使用的SON:

  1. from bson.son import SON
  2. pipeline = [
  3. {"$unwind": "$tags"},
  4. {"$group": {"_id": "$tags", "count": {"$sum": 1}}},
  5. {"$sort": SON([("count", -1), ("_id", -1)])}
  6. ]
  7. list(db.things.aggregate(pipeline))
  8. [{u'count': 3, u'_id': u'cat'}, {u'count': 2, u'_id': u'dog'}, {u'count': 1, u'_id': u'mouse'}]

可以使用command()方法 运行一个聚合explain方法:

  1. db.command('aggregate', 'things', pipeline=pipeline, explain=True)
  2. {u'ok': 1.0,
  3. u'stages': [{u'$cursor': {u'fields': {u'_id': 0, u'tags': 1},
  4. u'query': {},
  5. u'queryPlanner': {u'indexFilterSet': False,
  6. u'namespace': u'aggregation_example.things',
  7. u'parsedQuery': {u'$and': []},
  8. u'plannerVersion': 1,
  9. u'rejectedPlans': [],
  10. u'winningPlan': {u'direction': u'forward',
  11. u'filter': {u'$and': []},
  12. u'stage': u'COLLSCAN'}}}},
  13. {u'$unwind': {u'path': u'$tags'}},
  14. {u'$group': {u'_id': u'$tags', u'count': {u'$sum': {u'$const': 1}}}},
  15. {u'$sort': {u'sortKey': {u'_id': -1, u'count': -1}}}],
  16. u'waitedMS': 0L}

执行 explain=False

  1. db.command('aggregate', 'things', pipeline=pipeline, explain=False)
  2. {u'ok': 1.0,
  3. u'result': [{u'_id': u'cat', u'count': 3},
  4. {u'_id': u'dog', u'count': 2},
  5. {u'_id': u'mouse', u'count': 1}],
  6. u'waitedMS': 0L}