mongodb的python接口pymongo使用
1. 连接
from pymongo import MongoClient client = MongoClient("mongodb://mongodb0.example.net:27019") # client = MongoClient() db = client['primer'] coll = db.dataset # coll = db['dataset']
2. 插入
from datetime import datetime result = db.restaurants.insert_one( { "address": { "street": "2 Avenue", "zipcode": "10075", "building": "1480", "coord": [-73.9557413, 40.7720266] }, "borough": "Manhattan", "cuisine": "Italian", "grades": [ { "date": datetime.strptime("2014-10-01", "%Y-%m-%d"), "grade": "A", "score": 11 }, { "date": datetime.strptime("2014-01-16", "%Y-%m-%d"), "grade": "B", "score": 17 } ], "name": "Vella", "restaurant_id": "41704620" } )
3. 查找
cursor = db.restaurants.find({"address.zipcode": "10075"})
for document in cursor:
print(document)
cursor = db.restaurants.find(
{"$or": [{"cuisine": "Italian"}, {"address.zipcode": "10075"}]})
4. 排序输出
import pymongo cursor = db.restaurants.find().sort([ ("borough", pymongo.ASCENDING), ("address.zipcode", pymongo.DESCENDING) ])
5. 更新
result = db.restaurants.update_many( {"address.zipcode": "10016", "cuisine": "Other"}, { "$set": {"cuisine": "Category To Be Determined"}, "$currentDate": {"lastModified": True} } )
print result.modified_count
10
6. 删除
result = db.restaurants.delete_many({"borough": "Manhattan"})
print result.deleted_count
7. 聚合
Group Documents by a Field and Calculate Count
Use the $group stage to group by a specified key. In the $group stage, specify the group by key in the _id field. $group accesses fields by the field path, which is the field name prefixed by a dollar sign $. The $group stage can use accumulators to perform calculations for each group. The following example groups the documents in the restaurants collection by the borough field and uses the $sum accumulator to count the documents for each group.
cursor = db.restaurants.aggregate( [ {"$group": {"_id": "$borough", "count": {"$sum": 1}}} ] )
每天一小步,人生一大步!Good luck~