参考文档:
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. attintion: 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()
时间: 2024-10-26 20:44:34