Python MongoDB Search

In MongoDB, we use the find and findOne methods to find data in the collection.

Just like the SELECT statement is used to find data in tables of MySQL databases.

Find an item

To select data from a collection in MongoDB, we can use find_one() Method.

find_one() The method returns the first matching item in the selection.

Example

Find the first document in the "customers" collection:

import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
x = mycol.find_one()
print(x)

Run Example

Find all

To select data from a table in MongoDB, we can also use find() Method.

find() The method returns all the matching items in the selection.

find() The first parameter of the method is the query object. In this example, we used an empty query object, which selects all documents in the collection.

find() The method does not provide any parameters that would yield the same result as SELECT * in MySQL.

Example

Returns all documents in the "customers" collection and prints each document:

import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
for x in mycol.find():
  print(x)

Run Example

Only returns certain fields

find() The second parameter of the method is an object describing the fields included in the result.

This parameter is optional. If omitted, all fields will be included in the results.

Example

Only return names and addresses, not _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)

Run Example

It is not allowed to specify 0 and 1 values at the same time in the same object (unless one of the fields is the _id field). If a field with a value of 0 is specified, all other fields will have a value of 1, and vice versa:

Example

This example excludes "address" from the results:

import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
for x in mycol.find({},{ "address": 0 }):
  print(x)

Run Example

Example

An error will occur if 0 and 1 values are specified at the same time in the same object (unless one of the fields is the _id field):

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)