zoukankan      html  css  js  c++  java
  • 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~
  • 相关阅读:
    luogu P3239 [HNOI2015]亚瑟王
    android之软件键盘
    Eclipse输入智能提示设置
    防止反编译
    二进制数据读写
    数据类型转换
    类对象的读写文件
    Eclipse 快捷键
    修改IP
    Android eclipse 运行项目设置程序默认安装到SD卡
  • 原文地址:https://www.cnblogs.com/jkmiao/p/5173536.html
Copyright © 2011-2022 走看看