首页 > 数据库技术 > 详细

mongodb的python接口pymongo使用

时间:2016-01-31 20:59:34      阅读:229      评论:0      收藏:0      [点我收藏+]

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}}}
    ]
)

 

mongodb的python接口pymongo使用

原文:http://www.cnblogs.com/jkmiao/p/5173536.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!