Python MongoDB Find Document - Select, Query, Sort, and Limit
Its very easy to select or find document from a mongodb collection. Python provides many useful methods to select and filter documents from a collection.
Finding documents in MongoDB is equal to SELECT
query in Mysql.
We list few methods, which is used to select, filter, sort, and limit documents in a mongodb collection.
- The
find()
method is used to select and filter multiple documents from query results. - The
find_one()
method is used to return only one document (first document) from query results. - The
sort()
method is used to arrange the results in ascending or descending order. - The
limit()
method is used limit the number of results to be return from query results.
We will take a sample collection called "emp" from "mydatabase" and it contains four columns ("id", "name", "city", and "salary") and five documents.
{'_id': 2, 'name': 'bb', 'city': 'tokyo', 'salary': 3500}
{'_id': 3, 'name': 'cc', 'city': 'london', 'salary': 7000}
{'_id': 4, 'name': 'dd', 'city': 'paris', 'salary': 6000}
{'_id': 5, 'name': 'ee', 'city': 'london', 'salary': 1000}
Find One Document - The find_one() Method
We can use the find_one()
method to choose data from a collection on MongoDB.
The find_one()
method returns the selection's first occurrence.
Example :- Find the initial employee collection document :
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["emp"]
x = mycol.find_one()
print(x)
Output :-
Find All Documents - The find() Method
We can also use the find()
method to choose data from a table in MongoDB.
The find()
process returns all the selection occurrences.
The find()
method has two arguments:
- Query Object :- It is used to filter the documents like
WHERE
clause in Mysql - List Of Fields :- It is used to display some fields (insteadof all fields) from a document in the result like SELECT column1, column2... in Mysql.
A query object is the first parameter of the find()
function. We use a empty query object in this example, which selects all documents in the collection.
The same result as SELECT * in MySQL, you get without parameters of the find()
method.
Example :- Return all "employees" documents and print out each document :
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["emp"]
for x in mycol.find():
print(x)
Output :-
{'_id': 2, 'name': 'bb', 'city': 'tokyo', 'salary': 3500}
{'_id': 3, 'name': 'cc', 'city': 'london', 'salary': 7000}
{'_id': 4, 'name': 'dd', 'city': 'paris', 'salary': 6000}
{'_id': 5, 'name': 'ee', 'city': 'london', 'salary': 1000}
Return Only Some Fields
An object describes which fields to include in the result is the second parameter of find()
method.
This parameter is optional and all fields are included with the result if they are omitted.
Example 1 :- Return only the name and salary fields :
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["emp"]
for x in mycol.find({},{ "_id": 0, "name": 1, "salary": 1 }):
print(x)
Output :-
{'name': 'bb', 'salary': 3500}
{'name': 'cc', 'salary': 7000}
{'name': 'dd', 'salary': 6000}
{'name': 'ee', 'salary': 1000}
Remember
In the query parameter you are not permitted to enter either 0 or 1 values together.
It is possible only when the field list contains _id
field.
If a field with the value 0 is specified, all other fields are given value 1, and vice versa.
Example 2 :- This example will exclude name from the result :
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["emp"]
for x in mycol.find({},{ "name": 0 }):
print(x)
Output :-
{'_id': 2, 'city': 'tokyo', 'salary': 3500}
{'_id': 3, 'city': 'london', 'salary': 7000}
{'_id': 4, 'city': 'paris', 'salary': 6000}
{'_id': 5, 'city': 'london', 'salary': 1000}
Example 3 :- If both value 0 and value 1 is specified in the same object (except for the _id
field), you will get an error :
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["emp"]
for x in mycol.find({},{ "name": 1, "salary": 0 }):
print(x)
Filter the Result
You can filter the result by using a query object while locating document in a collection.
A query object is the first argument in the find()
method to limit searching.
Example 1:- Find document(s) with the city = "paris" :
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["emp"]
myquery = { "city": "paris" }
mydoc = mycol.find(myquery)
for x in mydoc:
print(x)
Output :-
{'_id': 4, 'name': 'dd', 'city': 'paris', 'salary': 6000}
Example 2:- Find document(s) with the salary > 5000 :
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["emp"]
myquery = { "salary": {"$gt": 5000} }
mydoc = mycol.find(myquery)
for x in mydoc:
print(x)
Output :-
{'_id': 4, 'name': 'dd', 'city': 'paris', 'salary': 6000}
Example 3:- Find document(s) with the city = paris and salary > 5000 and exclude _id field:
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["emp"]
myquery = { "city": "paris", "salary": {"$gt": 5000} }
myfield = {"_id": 0}
mydoc = mycol.find(myquery, myfield)
mydoc = mycol.find(myquery)
for x in mydoc:
print(x)
Output :-
Related Links
Filter With Regular Expressions
Regular expressions can also be used as a modification.
For querying strings, regular expressions may only be used.
Sort the Result
Use the sort()
method to sort the result in ascending or descending order.
The sort()
method uses the "fieldname" as a first parameter and a "direction" as a second parameter (ascending is the default direction).
Example :- Sort the result alphabetically by city :
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["emp"]
mydoc = mycol.find().sort("city")
for x in mydoc:
print(x)
Output :-
{'_id': 5, 'name': 'ee', 'city': 'london', 'salary': 1000}
{'_id': 1, 'name': 'aa', 'city': 'paris', 'salary': 2000}
{'_id': 4, 'name': 'dd', 'city': 'paris', 'salary': 6000}
{'_id': 2, 'name': 'bb', 'city': 'tokyo', 'salary': 3500}
Sort Descending
Use the -1 value to select the second descending parameter.
sort("city", 1) #ascending
sort("city", -1) #descending
Example :- Display the results in descending order based on salary field :
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["emp"]
mydoc = mycol.find().sort("salary", -1)
for x in mydoc:
print(x)
Output :-
{'_id': 4, 'name': 'dd', 'city': 'paris', 'salary': 6000}
{'_id': 2, 'name': 'bb', 'city': 'tokyo', 'salary': 3500}
{'_id': 1, 'name': 'aa', 'city': 'paris', 'salary': 2000}
{'_id': 5, 'name': 'ee', 'city': 'london', 'salary': 1000}
Related Links
Limit the Result
We utilise the limit()
method to limit the result of MongoDB.
A parameter is used with the limit()
method and a number defines how many documents should be returned.
Example :- Just return first 2 documents by limiting the result :
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["emp"]
myresult = mycol.find().limit(2)
for x in myresult:
print(x)
Output :-