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': 1, 'name': 'aa', 'city': 'paris', 'salary': 2000}
{'_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}

You can also search for these topics, python mongodb find ny id, multiple condition to find using python mongodb, check the python to find mongodb limit, how to sort the mongodb to find in python, replace the finding mangodb database in python, example for python mongodb find, python mongodb to find empty, define the specific field to find using python mongodb, use of keyerror using python mongodb find.

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 :-

{'_id': 1, 'name': 'aa', 'city': 'paris', 'salary': 2000}

You can also search for these topics, python find one element in list, mongodb findone() method in python, MongoDB collection to find one in python, return the python findone method, Example for python findone method.

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:

  1. Query Object :- It is used to filter the documents like WHERE clause in Mysql
  2. 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': 1, 'name': 'aa', 'city': 'paris', 'salary': 2000}
{'_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}

You can also search for these topics, python find all element in list, mongodb findall() method in python, MongoDB collection to findall in python, return the python findall method, Example for python findall method.

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': 'aa', 'salary': 2000}
{'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': 1, 'city': 'paris', 'salary': 2000}
{'_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)
You can also search for these topics, python return only some fields at once, return some fields by value using python, multiple values some fields using python mongodb, python object and functions to return only some field, parameters to return some fields with python mongodb.

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': 1, 'name': 'aa', 'city': 'paris', 'salary': 2000}
{'_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': 3, 'name': 'cc', 'city': 'london', 'salary': 7000}
{'_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 :-

{'name': 'dd', 'city': 'paris', 'salary': 6000}

You can also search for these topics, python mongodb find the result all, python mongodb find the result condition, python mongodb find the result example, python mongodb find the result equal, python mongodb find the result projection, python mongodb find the result range, python mongodb find the result show all, python mongodb find the result using.

Filter With Regular Expressions

Regular expressions can also be used as a modification.

For querying strings, regular expressions may only be used.

You can also search for these topics, python filter with regular expressions examples, filter all matches with regular expressions in python, how to combine the filter with python regular expressions, how to python mongodb findall the filter with regular expressions, match the python mongodb filter with regular expressions.

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': 3, 'name': 'cc', 'city': 'london', 'salary': 7000}
{'_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}

You can also search for these topics, python mongodb sort limit, mongodb sort by field in python, how to count the sort in python mongodb, example for sorting in python mongodb, find the python mongodb sort, how to get python mongodb sort collection, keyerror in the python mongodb sort, sort not working using python mongodb.

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': 3, 'name': 'cc', 'city': 'london', 'salary': 7000}
{'_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}

You can also search for these topics, python mongodb sort descending by date, collection of python sort descending, example for python sort descending, how to python to find sort descending, python key value to descending sorting, check the limit of the sorting descending order, working of multiple condition in python sort descending.

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 :-

{'_id': 1, 'name': 'aa', 'city': 'paris', 'salary': 2000} {'_id': 2, 'name': 'bb', 'city': 'tokyo', 'salary': 3500}

You can also search for these topics, python mongodb limit the result count, python mongodb limit the result example, how to find the python mongodb results are limited, methods in python mongodb limit the result, process the python mongodb limit, how to return the limit the result using python, how to update the results to python mongodb limit, validate the limit the result using mongodb python.