Python MongoDB 查找

在 MongoDB 中,我們使用 find 和 findOne 方法來查找集合中的數據。

就像 SELECT 語句用于查找 MySQL 數據庫中的表中的數據一樣。

查找一項

如需在 MongoDB 中的集合中選取數據,我們可以使用 find_one() 方法。

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() 方法的第一個參數是 query 對象。在這個例子中,我們用了一個空的 query 對象,它會選取集合中的所有文檔。

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() 方法的第二個參數是描述包含在結果中字段的對象。

此參數是可選的,如果省略,則所有字段都將包含在結果中。

實例

只返回姓名和地址,而不是 _ids:

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)

運行實例

不允許在同一對象中同時指定 0 和 1 值(除非其中一個字段是 _id 字段)。如果指定值為 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)