MongoDB的find

find: 查询数据

查询数据、修改数据、删除数据均可使用正则来进行条件筛选

一、基本使用

1、查询集合中的第一条数据

代码如下:

# coding:utf8
import pymongo as p

# 链接数据库
client = p.MongoClient("mongodb://localhost:27017")
# 进入数据库
mydb = client["love"]
student = mydb["users"]

# 查询集合中的第一条数据
x = student.find_one()
print(x)

结果如下:

image

2、查询指定字段的数据

代码如下:

# coding:utf8
import pymongo as p

# 链接数据库
client = p.MongoClient("mongodb://localhost:27017")
# 进入数据库
mydb = client["love"]
student = mydb["users"]

# 查询指定字段的数据, 需要显示的设置为1, 除了id , 0和1只能出现1个
# 如下就是只显示name和age字段,和student.find({}, {"_id": 0, "height": 0})作用一样
for v in student.find({}, {"_id": 0, "name": 1, "age": 1}):
    print(v)

结果如下:

image

3、使用过滤参数来进行筛选

代码如下:

# coding:utf8
import pymongo as p

# 链接数据库
client = p.MongoClient("mongodb://localhost:27017")
# 进入数据库
mydb = client["love"]
student = mydb["users"]

# 设置参数来过滤参数, 搜索name等于武成侯的数据,可使用正则来进行筛选。
for v in student.find({"name": "武成侯"}):
    print(v)

结果如下:

image

4、查询前4条数据

代码如下:

# coding:utf8
import pymongo as p

# 链接数据库
client = p.MongoClient("mongodb://localhost:27017")
# 进入数据库
mydb = client["love"]
student = mydb["users"]

for v in student.find().limit(4):
    print(v)

结果如下:

image

5、查询所有数据

代码如下:

# coding:utf8
import pymongo as p

# 链接数据库
client = p.MongoClient("mongodb://localhost:27017")
# 进入数据库
mydb = client["love"]
student = mydb["users"]

# 查询是有数据
for v in student.find():
    print(v)

结果如下:

image


读书和健身总有一个在路上

原文地址:https://www.cnblogs.com/Renqy/p/12850396.html