MongoDB中,我们使用find和findOne方法来查找集合中的数据。
就像MySQL数据库中的,我们使用SELECT语句查找表中的数据一样。
查找一个
要从集合中选取数据,可以使用find_one()
方法。
方法的作用是,返回选取项中的第一个记录。
示例
在customers集合中找到第一个文档:
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
x = mycol.find_one()
print(x)
查找全部
MongoDB中,要从表中选取数据,还可以使用find()
方法。
方法的作用是,返回选取项中出现的所有项。
find()
方法的第一个参数是一个查询对象。本例中,我们使用一个空查询对象,表示选取集合中的所有文档。
find()方法中,没有参数可以得到与MySQL中的 SELECT * 相同的结果。
示例
返回customers集合内所有文档,并打印:
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
for x in mycol.find():
print(x)
返回部分字段
find()
方法的第二个参数是一个对象,描述了结果中应包含哪些字段。
这个参数是可选的,如果省略,所有字段都将包含在结果中。
示例
只返回name
和address
,不返回_id
:
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
for x in mycol.find({},{ "_id": 0, "name": 1, "address": 1 }):
print(x)
字段值为1,表示包含,为0,表示排除。除了_id字段,参数中的其他字段值,要么全部是1,要么全部是0,不允许有的字段是0,有的是1值:
示例
此示例将从结果中排除“address”字段:
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
for x in mycol.find({},{ "address": 0 }):
print(x)
示例
如果参数中同时指定0和1的值,就会出现错误(除非其中一个字段是_id字段):
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
for x in mycol.find({},{ "name": 1, "address": 0 }):
print(x)