HomeBlogWeb DevelopmentMongoDB Query Document: Different Methods with Examples

MongoDB Query Document: Different Methods with Examples

Published
10th Apr, 2024
Views
view count loader
Read it in
8 Mins
In this article
    MongoDB Query Document: Different Methods with Examples

    Navigating the expansive terrain of MongoDB often poses a challenge for developers seeking specific data within a vast repository. In this context, `db.collection.find()` emerges as a reliable tool, simplifying the process of locating and retrieving precise documents. 

    My journey with the MongoDB query document has been marked by practical insights, and I want to share a personal experience that mirrors the common struggles developers face with the MongoDB find method. Picture a scenario where the need for extracting specific data from a massive database was met with traditional complexities. Enter `db.collection.find()`, a solution that not only streamlined the process but also enhanced the efficiency of MongoDB exploration. 

    Throughout this article, I'll leverage firsthand experiences to present case studies and examples, shedding light on the practical applications of `db.collection.find()` in the MongoDB query document. These instances, along with interviews and testimonies, aim to showcase the method as an invaluable asset in the MongoDB landscape. Join me as I delve into the intricacies of `db.collection.find()`, sharing insights garnered through expertise and real-world applications. 

    For more information, check out how to learn Full Stack Web development. 

    What is MongoDB Query? 

    In simple words, we use MongoDB Query when we need to retrieve a set of data from Collection. At its core, a MongoDB query is a request for specific information from the database. Unlike traditional relational databases, MongoDB employs a flexible, document-based structure, storing data in BSON format. A MongoDB query utilizes a rich set of operators and methods, with the db.collection.find() function playing a pivotal role in retrieving data. These queries can be tailored to filter, sort, and manipulate data according to specific criteria, providing developers with a dynamic and efficient means of interacting with their databases. Understanding MongoDB queries in Mongodb query documents is key to harnessing the full potential of this NoSQL database system in diverse application scenarios.  

    If you wish to master MongoDB with the understanding of basics and advanced concepts along with querying with MongoDB, then you can join the MongoDB Training course curated by experts of KnowledgeHut. 

    MongoDB's Flexible Schema

    A NoSQL database, which stands for "not only SQL," is a way of storing and retrieving data that is different from relational databases' traditional table structures (RDBMS). When storing large amounts of unstructured data with changing schemas, NoSQL databases are indeed a better option than RDBMS. Horizontal scaling properties of NoSQL databases allow them to store and process large amounts of data.

    These are intended for storing, retrieving, and managing document-oriented data, which is frequently stored in JSON format (JavaScript Object Notation). Document databases, unlike RDBMSs, have a flexible schema that is defined by the contents of the documents. MongoDB is one of the most widely used open-source NoSQL document databases. MongoDB is known as a 'schemaless' database because it does not impose a specific structure on documents in a collection.

    MongoDB is compatible with a number of popular programming languages. It also offers a high level of operational flexibility because it scales well horizontally, allowing data to be spread or 'sharded' across multiple commodity servers with the ability to add more servers as needed. MongoDB can be run on a variety of platforms, including developer laptops, private clouds, and public clouds.

    MongoDB Querying documents using find()

    MongoDB queries are used to retrieve or fetch data from a MongoDB database. When running a query, you can use criteria or conditions to retrieve specific data from the database. The function db.collection is provided by MongoDB. find() is a function that retrieves documents from a MongoDB database. In MongoDB, the find method is used to retrieve a specific document from the MongoDB collection. In Mongo DB, there are a total of six methods for retrieving specific records.

    • find()
    • findAndModify()
    • findOne()
    • findOneAndDelete()
    • findOneAndReplace()
    • findOneAndUpdate()

    Syntax:

    find(query, projection)

    We can fetch a specific record using the Find method, which has two parameters. If these two parameters are omitted, the find method will return all of the documents in the MongoDB collection.

    Example:

    Consider an example of employees with the database of employee_id and employee_name and we will fetch the documents using find() method.

    First, create a database with the name “employees” with the following code:

    use employees

    Now, create a collection “employee” with:

    db.createCollection("employee")

    In the next step we will insert the documents in the database:

    db.employee.insert([{employee_id: 101, employee_name: "Ishan"}, {employee_id: 102, employee_name: "Bhavesh"}, {employee_id: 103, employee_name: "Madan"}])

    Find all Documents:

    To get all the records in a collection, we need to use the find method with an empty parameter. In other words, when we need all the records, we will not use any parameters.

    db.employee.find()

    Output in Mongo Shell

    MongoDB Query Document using find() with Example

    The pretty() method can be used to display the results in a formatted manner.

    Syntax:

    db.COLLECTION_NAME.find().pretty()

    Let’s check our documents with pretty() method:

    MongoDB Query Document using find() with Example

    Query Filters

    We will see examples of query operations using the db.collection.find() method in mongosh.

    We will use the employee collection in the employees database.

    db.employee.insert([{employee_id: 101, employee_name: "Ishan", age: 21, email_id: "ishanjain@gmail.com"}, {employee_id: 102, employee_name: "Bhavesh", age: 22, email_id: "bhaveshg@gmail.com"}, {employee_id: 103, employee_name: "Madan", age: 23, email_id: "madan@gmail.com"}])

    As we have seen earlier that to select all the documents in the database we pass an empty document as the query filter parameter to the find method.

    Worried about how to start your career in web development? Enroll in Web Development basics course.   

    db.employee.find().pretty()

    MongoDB Query Document using find() with Example

    1. Find the first document in a collection:

    db.employee.findOne()

    MongoDB Query Document using find() with Example

    2. Find a document by ID:

    db.employee.findOne({_id : ObjectId("61d1ae0b56b92c20b423a5a7")})

    MongoDB Query Document using find() with Example

    3. Find Documents that Match Query Criteria

    db.employee.find({“age”: “22”})

    MongoDB Query Document using find() with Example

    db.employee.find({"employee_name": "Madan"}).pretty()

    MongoDB Query Document using find() with Example

    4. Sort Results by a Field:

    db.employee.find().sort({age: 1}).pretty()

    order by age, in ascending order

    MongoDB Query Document using find() with Example

    db.employee.find().sort({age: -1}).pretty()

    order by age, in descending order

    MongoDB Query Document using find() with Example

    AND Conditions:

    A compound query can specify conditions for multiple fields in the documents in a collection. A logical AND conjunction connects the clauses of a compound query indirectly, allowing the query to select all documents in the collection that meet the specified conditions.

    In the following example, we will consider all the documents in the employee collection where employee_id equals 101 and age equals 21.

    db.employee.find({"employee_id": 101, "age": "21" }).pretty()

    MongoDB Query Document using find() with Example

    Querying nested fields

    The embedded or nested document feature in MongoDB is a useful feature. Embedded documents, also known as nested documents, are documents that contain other documents.

    You can simply embed a document inside another document in MongoDB. Documents are defined in the mongo shell using curly braces (), and field-value pairs are contained within these curly braces.

    Using curly braces, we can now embed or set another document inside these fields, which can include field-value pairs or another sub-document.

    Syntax:

    { field: { field1: value1, field2: value2 } }

    Example:

    We have a database “nested” and in this database we have collection “nesteddoc”.

    The following documents will insert into the nesteddoc collection.

    db.nesteddoc.insertMany([ { "_id" : 1, "dept" : "A", "item" : { "sku" : "101", "color" : "red" }, "sizes" : [ "S", "M" ] }, { "_id" : 2, "dept" : "A", "item" : { "sku" : "102", "color" : "blue" }, "sizes" : [ "M", "L" ] }, { "_id" : 3, "dept" : "B", "item" : { "sku" : "103", "color" : "blue" }, "sizes" : "S" }, { "_id" : 4, "dept" : "A", "item" : { "sku" : "104", "color" : "black" }, "sizes" : [ "S" ] } ])

    Place the documents in the collection now. Also, take a look at the results:

    MongoDB Query Document using find() with Example

    As a result, the nesteddoc collection contains four documents, each of which contains nested documents. The find() method can be used to access the collection's documents.

    db.nesteddoc.find()

    MongoDB Query Document using find() with Example

    Specify Equality Condition:

    In this example, we will select the document from the nesteddoc query where dept equals “A”.

    db.nesteddoc.find({dept: "A"})

    MongoDB Query Document using find() with Example

    Querying Arrays

    Use the query document {<field>: <value>} to specify an equality condition on an array, where <value> is the exact array to match, including the order of the elements.

    The following query looks for all documents where the field tags value is an array with exactly two elements, "S" and "M," in the order specified:

    db.nesteddoc.find( { sizes: ["S", "M"] } )

    MongoDB Query Document using find() with Example

    Use the $all operator to find an array that contains both the elements "S" and "M," regardless of order or other elements in the array:

    db.nested.find( { sizes: { $all: ["S", "M"] } } )

    MongoDB Query Document using find() with Example

    Query an Array for an Element:

    The following example queries for all documents where size is an array that contains the string “S” as one of its elements:

    db.nesteddoc.find( { sizes: "S" } )

    MongoDB Query Document using find() with Example

    Filter conditions

    To discuss the filter conditions, we will consider a situation that elaborates this. We will start by creating a collection with the name “products” and then add the documents to it.

    db.products.insertMany([
    { _id: 1, item: { name: "ab", code: "123" }, qty: 15, tags: [ "A", "B", "C" ] },
    { _id: 2, item: { name: "cd", code: "123" }, qty: 20, tags: [ "B" ] },
    { _id: 3, item: { name: "ij", code: "456" }, qty: 25, tags: [ "A", "B" ] },
    { _id: 4, item: { name: "xy", code: "456" }, qty: 30, tags: [ "B", "A" ] },
    { _id: 5, item: { name: "mn", code: "000" }, qty: 20, tags: [ [ "A", "B" ], "C" ] }])

    To check the documents, use db.products.find():

    MongoDB Query Document using find() with Example

    1. $gt

    $gt selects documents with a field value greater than (or equal to) the specified value.

    db.products.find( { qty: { $gt: “20” } } )

    MongoDB Query Document using find() with Example

    2. $gte:

    $gte finds documents in which a field's value is greater than or equal to (i.e. >=) a specified value (e.g. value.)

    db.products.find( { qty: { $gte: 20 } } )

    MongoDB Query Document using find() with Example

    3. $lt:

    $lt selects documents whose field value is less than (or equal to) the specified value.

    db.products.find( { qty: { $lt: 25 } } )

    MongoDB Query Document using find() with Example

    4. $lte:

    $lte selects documents in which the field's value is less than or equal to (i.e. =) the specified value.

    db.products.find( { qty: { $lte: 20 } } )

    MongoDB Query Document using find() with Example

    Query an Array by Array Length:

    To find arrays with a specific number of elements, use the $size operator. For example, the following selects documents with two elements in the array.

    db.products.find( { "tags": {$size: 2} } )

    MongoDB Query Document using find() with Example

    Unleash your coding potential with our Python learning online course. Master the language that powers tech giants and opens doors to endless opportunities. Join now!

    MongoDB Query Operators

    Imagine a MongoDB collection, `employees`, where each document encapsulates information about employees, such as `name`, `department`, and `salary`. This fictional dataset provides a practical backdrop to explore the effective use of MongoDB query document using mongodb db find with querying operators. We will see various db collection find example below with different operators.

    AND in MongoDB 

    The `$and` operator in the MongoDB query document proves invaluable when precision matters. If we aim to find employees in the "Marketing" department with a salary above $50,000, using `$and` allows us to succinctly express both conditions. This operator is particularly useful in scenarios where you need to find all the documents in Mongodb that fulfill multiple criteria for accurate results. 

    Syntax: db.collection.find({ $and: [ { condition1 }, { condition2 }, ... ] }) 
    Query: db.employees.find({ $and: [ { department: "Marketing" }, { salary: { $gt: 50000 } } ] }) 

    OR in MongoDB 

    Conversely, the `$or` operator in the MongoDB query document broadens our search parameters. In situations where we want to retrieve documents for employees either from the "Sales" department or those with a salary exceeding $60,000, `$or` allows for flexibility in defining multiple conditions. 

    Syntax: db.collection.find({ $or: [ { condition1 }, { condition2 }, ... ] }) 
    Query: db.employees.find({ $or: [ { department: "Sales" }, { salary: { $gt: 60000 } } ] }) 

    Using AND and OR Together 

    Combining `$and` and `$or` in a MongoDB query document enhances query complexity, which is useful when seeking nuanced information. For instance, to fetch Marketing employees with a salary above $50,000 or Sales employees regardless of their salary, the combined use of both operators provides a powerful solution. 

    Syntax: db.collection.find({ $and: [ { condition1 }, { $or: [ { subCondition1 }, { subCondition2 }, ... ] } ] }) 
    Query: db.employees.find({ $and: [ { department: "Marketing" }, { $or: [ { salary: { $gt: 50000 } }, { department: "Sales" } ] } ] }) 

    NOR in MongoDB 

    The `$nor` operator in the MongoDB query document comes into play when exclusion is the goal. For example, to find employees not in the "IT" department or those earning below $70,000, `$nor` efficiently excludes documents meeting specific conditions. 

    Syntax: db.collection.find({ $nor: [ { condition1 }, { condition2 }, ... ] }) 
    Query: db.employees.find({ $nor: [ { department: "IT" }, { salary: { $lt: 70000 } } ] }) 

    NOT in MongoDB 

    The `$not` operator in the MongoDB query document proves useful for negating a specific condition. Suppose we wish to fetch employees who are not earning $60,000. Utilizing `$not` in this context streamlines the query. 

    Syntax: db.collection.find({ field: { $not: { $operator: value } } }) 
    Query: db.employees.find({ salary: { $not: { $eq: 60000 } } }) 

    Understanding when to use each operator is pivotal in crafting effective queries. Employ `$and` for precision, `$or` for versatility, combine them judiciously, turn to `$nor` for exclusions, and leverage `$not` to invert conditions, all based on the unique requirements of your data exploration journey in MongoDB. 

    Projection

    In MongoDB, projection refers to selecting only the data that is required rather than the entire document's data. If a document has five fields and you only want to show three of them, select only three of them.

    The find() method in MongoDB accepts a second optional parameter, which is a list of fields to retrieve, as explained in MongoDB Query Document. When you use the find() method in MongoDB, it displays all of a document's fields. To prevent this, create a list of fields with the values 1 or 0. The value 1 indicates that the field should be visible, while 0 indicates that it should be hidden.

    Syntax:

    db.COLLECTION_NAME.find({},{KEY:1})

    Example:

    We will consider the previous example of product collection. Run the below command on Mongoshell to learn how projection works:

    db.products.find({},{"tags":1, _id:0})

    MongoDB Query Document using find() with Example

    Keep in mind that the _id field is always displayed while executing the find() method; if you do not want this field to be displayed, set it to 0.

    RDBMS Where Clause Equivalents in MongoDB

    Let us chart out a comparative table that lists out various operators with where condition in both RDBMS and Mongo DB Queries. This will help us relate our mongo queries to rdbms and understand them better. Please refer the table below 

    Operation 

     

    MongoDB Syntax 

    MongoDB Example 

    RDBMS Equivalent 

    AND 

     

    { $and: [ { price: { $gt: 50 } }, { category: "Electronics" } ] } 

     

    db.products.find({ $and: [ { price: { $gt: 50 } }, { category: "Electronics" } ] }) 

     

    SELECT * FROM products_table WHERE price > 50 AND category = 'Electronics'; 

     

    IS NOT NULL 

     

    { stock_quantity: { $ne: null } } 

     

    db.products.find({ stock_quantity: { $ne: null } }) 

     

    SELECT * FROM products_table WHERE stock_quantity IS NOT NULL; 

     

    BETWEEN 

     

    { price: { $gte: 30, $lte: 80 } } 

     

    db.products.find({ price: { $gte: 30, $lte: 80 } }) 

     

    SELECT * FROM products_table WHERE price BETWEEN 30 AND 80; 

     

    IN 

     

    { category: { $in: ['Electronics', 'Clothing'] } } 

     

    db.products.find({ category: { $in: ['Electronics', 'Clothing'] } }) 

     

    SELECT * FROM products_table WHERE category IN ('Electronics', 'Clothing'); 

     

    NOT IN 

     

    { category: { $nin: ['Electronics', 'Clothing'] } } 

     

    db.products.find({ category: { $nin: ['Electronics', 'Clothing'] } }) 

     

    SELECT * FROM products_table WHERE category NOT IN ('Electronics', 'Clothing'); 

     

    LIKE 

     

    { name: /Laptop/ } 

     

    db.products.find({ name: /Laptop/ }) 

     

    SELECT * FROM products_table WHERE name LIKE '%Laptop%'; 

     

    OR 

     

    { $or: [ { price: { $lt: 30 } }, { stock_quantity: { $eq: 0 } } ] } 

     

    db.products.find({ $or: [ { price: { $lt: 30 } }, { stock_quantity: { $eq: 0 } } ] }) 

     

    SELECT * FROM products_table WHERE price < 30 OR stock_quantity = 0; 

     

    NOT 

     

    { $not: { price: { $gt: 100 } } } 

     

    db.products.find({ $not: { price: { $gt: 100 } } }) 

     

    SELECT * FROM products_table WHERE NOT (price > 100); 

     

     These examples cover a variety of scenarios, including conditions such as IN, NOT IN, LIKE, OR, and NOT, providing practical MongoDB queries and their RDBMS equivalents. Adjust these queries based on your specific use case and data structure. 

    Optimized Findings

    • To retrieve a document from a MongoDB collection, use the Find method.
    • Using the Find method, we can retrieve specific documents as well as the fields that we require. Other find methods can also be used to retrieve specific documents based on our needs.
    • By inserting array elements into the query, we can retrieve specific elements or documents. To retrieve data for array elements from the collection in MongoDB, we can use multiple query operators.

    Conclusion

    In MongoDB querying, we've embarked on a journey through its flexible schema, unveiling the power of the `db.collection.find()` method in mongodb query document. From filtering documents to navigating nested fields and arrays, MongoDB's querying prowess stands out. The exploration of logical operators—AND, OR, NOR, and NOT—has illuminated the syntax and examples, offering a comprehensive understanding. As we bridged the gap between MongoDB and relational databases, the table of RDBMS equivalents provided a valuable guide. 

    Optimizing findings and projections further enhanced the efficiency of MongoDB queries. In this dynamic interplay of structure and flexibility, MongoDB emerges as a robust solution for modern data management. Whether you're well-versed in traditional databases or delving into NoSQL territory, this KnowledgeHut MongoDB training empowers you to harness the full potential of MongoDB's querying capabilities, bridging the gap between structured and unstructured data paradigms.  

    Profile

    Abhresh Sugandhi

    Author

    Abhresh is specialized as a corporate trainer, He has a decade of experience in technical training blended with virtual webinars and instructor-led session created courses, tutorials, and articles for organizations. He is also the founder of Nikasio.com, which offers multiple services in technical training, project consulting, content development, etc.

    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Select
    Your Message (Optional)

    Upcoming Web Development Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon