Pymongo articles

1. Connect

import pymongo

# 连接数据库
mongo_clien = pymongo.MongoClient(host="127.0.0.1", port=27017)
MONGO = mongo_clien['day0217']

res = list(MONGO.user_info.find({}))

print(res)

print out data:
Here Insert Picture Description
but we will check out the data, you will find, res like in Python dictionaries, but when we json.dumps (res) time, you will find the program error (TypeError: Object of type ' ObjectId 'is not JSON serializable). Here Insert Picture Description
At this point we will "_id" translated into strings look, the success of the program will print out the data.
Here Insert Picture Description
== But when we query data, if you do not use Objectid to query if the same will error, so now we need to have an idea that, when we use mongodb data query data, we want to use Objectid, in our data we want to take time out of use str.

Summarized as follows:

import pymongo
from bson import ObjectId
import json

# 连接数据库
mongo_clien = pymongo.MongoClient(host="127.0.0.1", port=27017)
MONGO = mongo_clien['day0217']

res = MONGO.user_info.find_one({"id":1})

#这里在查询数据
res_obj = MONGO.user_info.find_one({"_id":ObjectId(res["_id"])})
print(res_obj)

#这里在提取数据
res["_id"] = str(res["_id"])
res_json = json.dumps(res)
print(res_json)

2. The basic operation of pymongo

#查
res = list(MONGO.user_info.find({"$or":[{"name":"cyx"},{"id":1}]}))
# print(res)

#增
res = MONGO.user_info.insert_one({"name":"shazi","age":666})
res = MONGO.user_info.insert_many([ {"name":"zxc","age":741},{"name":"asf","age":456} ])
# print(res,res.inserted_ids)

#改
res = MONGO.user_info.update_one({"name":"shazi"},{"$set":{"name":"bushishazi","id":3}})
# print(res)

#删
res = MONGO.user_info.delete_many({"name":"shazi"})
print(res)

#print(res)

3. Advanced operation in pymongo

#高级用法
res = list(MONGO.user_info.find({}).limit(5))
res2 = list(MONGO.user_info.find({}).limit(5).skip(5))
res3 = list(MONGO.user_info.find({}).sort("id",pymongo.ASCENDING))
print(res)

4. advantage of py

Here Insert Picture Description

Published 12 original articles · won praise 7 · views 168

Guess you like

Origin blog.csdn.net/caiyongxin_001/article/details/104748131