pymongo 학습 제1 편-첨삭 검사

참고 문서:
1、https://docs.mongodb.org/getting-started/python/
2、http://api.mongodb.org/python/current/api/pymongo/index.html
 
# -*- coding: utf-8 -*-
import sys
from datetime import datetime
from pymongo import MongoClient
import pymongo
import re

def main():
    '''connect to database.
            client = MongoClient()   client = MongoClient("localhost:27017")
    '''
    client = MongoClient()
    db = client.demo
    coll = db.address

    '''insert data.
        insert_one()
        insert_many()
    '''
    insertResult = coll.insert_one({
        "account": "[email protected]",
        "password": "123456",
        "birth": datetime.strptime("1990-09-22", "%Y-%m-%d"),
        "score": 102,
        "address": {"city": ["beijing", "wuxi", "chengdu"], "country": "China"},
        "articles": [{"title": "mongo      ", "author": "xiaomaque"},
                    {"title": "mysql  ", "author": "ponpon7"}]
    })
    print(insertResult.inserted_id)
    elements = [{"account": "ponpon7", "password": "afi89^^R", "birth": datetime.strptime("1986-12-12", "%Y-%m-%d"), "score": 172}, {"account": "liudehua", "password": "wangqingshui", "birth": "", "score": 18}]
    coll.insert_many(elements)

    '''find or query data.
        cursorAll:   score<140   ,   account    , score      . $lt: less than<; $gt: greater than>
        cursorOr: logical OR
        cursorRegex:          
    '''
    cursorAll = coll.find({"score": {"$lt": 140}}).sort([
        ("account", pymongo.ASCENDING),
        ("score", pymongo.DESCENDING)
    ])
    for document in cursorAll:
        print("All document: {}".format(document))

    cursorRegex = coll.find({"account": re.compile('p', re.I)})
    for document in cursorRegex:
        print("Regex document: {}".format(document))

    cursorOr = coll.find({"$or": [{"score": 172}, {"address.country": "China"}]})
    for document in cursorOr:
        print("score is 172 Or country is China: {}".format(document))

    '''update data & replace data.
        update_one(filter, update, upsert=False, bypass_document_validation=False)
            upsert:    True,     filter         ,   false
    '''
    updateResult = coll.update_many(
        {"account": "[email protected]"},
        {
            "$set": {"score": 129, "address": {"city": ["nanjing"], "country": "China"}},
            "$currentDate": {"lastModified": True}
        },
        # True
    )
    print("update: matched_count is {}".format(updateResult.matched_count))
    print("update: modified_count is {}".format(updateResult.modified_count))

    replaceResult = coll.replace_one(
        {"account": "[email protected]"},
        {
            "account": "[email protected]",
            "score": 139,
            "address": {"city": ["Paris"], "country": "France"},
        }
    )
    print("replace: matched_count is {}".format(replaceResult.matched_count))
    print("replace: modified_count is {}".format(replaceResult.modified_count))

    '''remove data.
        Attention: delete_many({})  delete all documents
                    coll.drop()  drop a collection
    '''
    deleteResult = coll.delete_many({"birth": datetime.strptime("1990-09-22", "%Y-%m-%d")})
    print("remove: deleted_count is {}".format(deleteResult.deleted_count))


if __name__ == '__main__':
    main()
 

좋은 웹페이지 즐겨찾기