MongoDB is a NoSQL document-oriented database. It does not give much importance for relations or can also be said as it is schema-free.
PyMongo is a Python module that can be used to interact between the mongo database and Python applications. The data that is exchanged between the Python application and the mongo database is in Binary JSON format.
Nested Queries in PyMongo
To fetch a particular record from the MongoDB document, querying plays an important role. Getting the right data as soon as possible to make the right decision is necessary. Here are some of the multiple query request techniques.
Query operators in PyMongo
To use
$and,
$or and
$not MongoDB operators, the outer dictionary key must be one of the query operators; and dictionary parameters must be in a Python list and that Python list must be the value of the key.
Syntax :
query = {
'$and' : [
{ operand_query_1},
{ operand_query_2}
]
}
Example 1 : Create a collection called lecturers and retrieve using
find().
Output :
👁 Image
Query 1 : Display the lecturer records with salary less than 50000 and arrange in ascending order.
Output :
👁 Image
Query 2 : Display lecturer records with salary greater than 40000 in department_id 1 and sort according to their salary in descending order.
Output :
👁 Image
Example 2 : Create a collection called books and retrieve using
find().
Output :
👁 Image
Query 1 : Display the record of books with ratings greater than 3 published after 2000.
Output :
👁 Image
Query 2 : Display the record of the books with ratings greater than 1 and published between the year 1999 and 2016, sort in decreasing order.