标签:字典 相关 span pre 2.0 一个 命令行 code 生成
mongo_db 类似于 服务器命令行的db
我们可以db.user.find() 查询
find()
需要加上列表
import pymongo mongo_client = pymongo.MongoClient( host=‘192.168.0.112‘, port=27017, username="admin", password="123456" ) mongo_db = mongo_client["db1"] # 查询 res = mongo_db.user.find() res = list(res) print(res)
返回结果,和服务器一样的
[ {‘_id‘: ObjectId(‘5ca7a4b0219efd687462f965‘), ‘id‘: 1.0, ‘name‘: ‘jack‘, ‘age‘: 73.0}, {‘_id‘: ObjectId(‘5ca7a4b7219efd687462f966‘), ‘id‘: 2.0, ‘name‘: ‘mike‘, ‘age‘: 84.0, ‘gender‘: ‘男‘}, {‘_id‘: ObjectId(‘5ca7a4c4219efd687462f967‘), ‘id‘: 3.0, ‘name‘: ‘peter‘, ‘age‘: 21.0}, {‘_id‘: ObjectId(‘5ca7a4c4219efd687462f968‘), ‘id‘: 4.0, ‘name‘: ‘xiaogang‘, ‘age‘: 34.0, ‘hobby‘: [‘篮球‘]}, {‘_id‘: ObjectId(‘5ca7a4c4219efd687462f969‘), ‘id‘: 5.0, ‘name‘: ‘ben‘, ‘age‘: 24.0}, {‘_id‘: ObjectId(‘5ca7a505219efd687462f96a‘), ‘id‘: 6.0, ‘name‘: ‘Mary‘, ‘age‘: 84.0, ‘gender‘: ‘男‘} ]
find_one()方法:
import pymongo # 生成pymongo对象,传入连接服务器相关参数 ip 端口 mongo_client = pymongo.MongoClient( host=‘192.168.0.112‘, port=27017, username="admin", password="123456" ) # 选择连接的数据库 mongo_db = mongo_client["db1"] # 查询 res = mongo_db.user.find_one() print(res)
和findOne效果一样,返回第一条数据
{‘_id‘: ObjectId(‘5ca7a4b0219efd687462f965‘), ‘id‘: 1.0, ‘name‘: ‘jack‘, ‘age‘: 73.0}
是一个字典可以取
import pymongo # 生成pymongo对象,传入连接服务器相关参数 ip 端口 mongo_client = pymongo.MongoClient( host=‘192.168.0.112‘, port=27017, username="admin", password="123456" ) # 选择连接的数据库 mongo_db = mongo_client["db1"] # 查询 res = mongo_db.user.find_one() print(res.get("_id")) # 5ca7a4b0219efd687462f965
循环对象,循环比加list好,因为res是生成器,效率高
import pymongo mongo_client = pymongo.MongoClient( host=‘192.168.0.112‘, port=27017, username="admin", password="123456" ) mongo_db = mongo_client["db1"] # 查询 res = mongo_db.user.find() print(res) for i in res: print(i)
是一个生成器,
<pymongo.cursor.Cursor object at 0x0000000002EC2DA0>
{‘_id‘: ObjectId(‘5ca7a4b0219efd687462f965‘), ‘id‘: 1.0, ‘name‘: ‘jack‘, ‘age‘: 73.0} {‘_id‘: ObjectId(‘5ca7a4b7219efd687462f966‘), ‘id‘: 2.0, ‘name‘: ‘mike‘, ‘age‘: 84.0, ‘gender‘: ‘男‘} {‘_id‘: ObjectId(‘5ca7a4c4219efd687462f967‘), ‘id‘: 3.0, ‘name‘: ‘peter‘, ‘age‘: 21.0} {‘_id‘: ObjectId(‘5ca7a4c4219efd687462f968‘), ‘id‘: 4.0, ‘name‘: ‘xiaogang‘, ‘age‘: 34.0, ‘hobby‘: [‘篮球‘]} {‘_id‘: ObjectId(‘5ca7a4c4219efd687462f969‘), ‘id‘: 5.0, ‘name‘: ‘ben‘, ‘age‘: 24.0} {‘_id‘: ObjectId(‘5ca7a505219efd687462f96a‘), ‘id‘: 6.0, ‘name‘: ‘Mary‘, ‘age‘: 84.0, ‘gender‘: ‘男‘}
条件查询
import pymongo mongo_client = pymongo.MongoClient( host=‘192.168.0.112‘, port=27017, username="admin", password="123456" ) mongo_db = mongo_client["db1"] # 条件查询 res = mongo_db.user.find_one({"age":34}) print(res) # {‘_id‘: ObjectId(‘5ca7a4c4219efd687462f968‘), ‘id‘: 4.0, ‘name‘: ‘xiaogang‘, ‘age‘: 34.0, ‘hobby‘: [‘篮球‘]}
标签:字典 相关 span pre 2.0 一个 命令行 code 生成
原文地址:https://www.cnblogs.com/mingerlcm/p/10699351.html