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)

 

posted @ 2019-01-16 19:44  逆欢  阅读(759)  评论(0编辑  收藏  举报