1、ObjectId与String相互转换
ObjectId类型 —→ String类型 这个非常简单,直接强制类型转换就可以了 _id = str(ObjectId('类型')) String类型 —→ ObjectId类型 from bson.objectid import ObjectId _id = ObjectId("字符串")
2、连接数据库
# 一、AsyncIOMotorClient 异步 DB_CLIENT = AsyncIOMotorClient('127.0.0.1', 27017) db = DB_CLIENT['xy'] # 库名称 # 二、pymongo 同步 server = "mongodb://127.0.0.1:27017" conn = pymongo.MongoClient(server) db1 = conn["xy"] xyuser = db1.get_collection('xyuser')
3、常用
一、ObjectId返回前端后,可以传参过来直接在_id字段使用 async def mongodb(oid: str, request: Request): oid = ObjectId('632bd220c66f6b200868ed6c') cursor = db.user.find({'_id': {'$eq': oid}}) # 返回cursor docs = await cursor.to_list(None) # 注意cursor的处理 print(str(docs[0].get('_id'))) 二、插入多个值,返回_id列表 docs = await Userorg.all().values() print(docs) insert_many = await db.userorg.insert_many(docs) print(insert_many.inserted_ids) return {'msg': repr(len(insert_many.inserted_ids))} 三、插入和返回多个值 result = await db.test.insert_many( [{'i': i} for i in range(200000)]) async for document in db.xyuser.find(): print(document) print('inserted %d docs' % (len(result.inserted_ids),))
标签:insert,经验,ObjectId,mongodb,db,学习,docs,print,id From: https://www.cnblogs.com/pearlcity/p/16719291.html