MongoDB 之pymongodb
Posted 逆欢
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MongoDB 之pymongodb相关的知识,希望对你有一定的参考价值。
import pymongo import json from bson import ObjectId mongoclient = pymongo.MongoClient(host="127.0.0.1",port=27017) #链接 MongoDB = mongoclient["locals"] #链接数据库名称 # res = MongoDB.user.find({}) # for i in res: # print(i) # i["_id"] = str(i.get("_id")) #ObjectId需要进行转换成字符串才能进行json()序列化 # print(i.get("_id"),type(i.get("_id"))) # s = json.dumps(i) # res = MongoDB.user.find_one({},{"_id":0}) # print(res) # res = list(MongoDB.user.find({"id":1})) # print(res) #增加 # res = MongoDB.user.insert_one({"id":1,"age":55,"name":"taibai"})#pycharm下都是_one # print(res,type(res),res.inserted_id) # res = MongoDB.user.insert_many([{"id":1,"age":55,"name":"taibai"},{"id":1,"age":55,"name":"taibai"}]) # print(res,type(res),res.inserted_ids) # 修改: # res = MongoDB.user.update_one({"age":55},{"$set":{"name":"四金"}})#并且$set需要加上"" # print(res,dir(res)) # MongoDB.user.update_many({"age":55},{"$set":{"name":"四金"}}) #删除: # res = MongoDB.user.delete_one({"id":1}) # res = MongoDB.user.delete_many({"id":1}) # sort limit skip # res = list(MongoDB.user.find({}).limit(5).skip(2)) # print(res) # res = list(MongoDB.user.find({}).sort("age",pymongo.DESCENDING).limit(5).skip(2)) # print(res) # s = ObjectId("5c3ea77e23652a0218a5ab9a") # # res = MongoDB.user.find_one({"_id":ObjectId("5c3ea77e23652a0218a5ab9a")}) # print(res)
以上是关于MongoDB 之pymongodb的主要内容,如果未能解决你的问题,请参考以下文章