Page Content

Tutorials

How do you Query Documents in MongoDB?

Query Documents

The main function in MongoDB for data retrieval is db.collection.find(). This flexible technique enables you to choose documents from a single collection according to predetermined standards, or conditions, that specify which data MongoDB ought to send back to the customer. In addition to basic selection, you can include a “projection” to indicate which fields from the matching documents you wish to view. By reducing the quantity of data delivered, this helps lower processing needs and network overhead. To better manage the result set, you can alter queries using functions like limit(), skip(), and sort().

The basic syntax for the find() method is straightforward: >db.COLLECTION_NAME.find().

Understanding the Cursor

The fact that find() returns a cursor rather than the actual documents—as a reference to the result set—is an important feature. The entire collection of related documents is stored in this iterable cursor.

To access cursor-returned documents, cycle across them. Without assigning the find() result to a variable using the var keyword, the MongoDB shell iterates and displays the top 20 documents. You can type it to get the next 20 documents if there are additional results. Additionally, you may use DBQuery.shellBatchSize to change the batch size that is set by default.

There are various cursor mechanisms available for manual iteration:

  1. cursor.next(): Advanced cursor position and returns the next document in the result set.
  2. cursor.hasNext(): Checks if the cursor can return more documents.
  3. cursor.forEach(<function>): This method applies a given JavaScript function to each document it returns after iterating through the entire pointer.
  4. cursor.toArray(): This function essentially exhausts the cursor by loading all documents that the cursor returns into RAM and returning them as an array.

Example of Cursor Iteration (Manual):

var myCursor = db.inventory.find({ type: 'food' }); // Assign to a variable to prevent auto-iteration
while (myCursor.hasNext()) {
    printjson(myCursor.next()); // printjson() is a helper for formatted output
}
// Or using forEach:
// myCursor.forEach(printjson);

The fact that cursors are not isolated during their lifetime should not be overlooked. A document may be returned more than once if write operations make changes to it while the cursor is active. The snapshot() method can be applied to a cursor to provide isolation in certain situations.

Pretty-Printing Results for Readability

The default output for find() in the MongoDB shell might occasionally be unstructured and challenging to comprehend when you query documents. It is possible to chain the.pretty() function to your find() action to display results in a more understandable and formatted manner.

Example of using .pretty():

db.mycol.find().pretty()

As with properly prepared JSON, this will show the documents with line breaks and appropriate indentation.

Querying for All Documents

To retrieve all documents in a collection, use the find() method with an empty query document ({}) as the first argument. Providing an empty query document is the same as completely omitting it.

Example of querying all documents:

db.COLLECTION_NAME.find()
// or
db.COLLECTION_NAME.find({})

Querying for Specific Documents using Query Selectors

You supply a query selection as the first argument to the find() method in order to get particular documents that meet predetermined criteria. A JSON object that specifies the requirements that documents must meet is called a query selector.

Basic Equality Match

The simplest query selection matches a field and its value exactly. Numbers, booleans, and strings match.

Example:

db.users.find({ "age": 27 }) // Finds documents where 'age' is exactly 27 
db.users.find({ "username": "joe" }) // Finds documents where 'username' is "joe" 

Implicit AND Conditions

MongoDB handles multiple key value pairs as an implicit AND condition when you include them in a single query selection. A document cannot be returned until all of the requirements are met.

Example:

db.users.find({ "username": "joe", "age": 27 }) // Finds users who are "joe" AND 27 years old 

Comparison Operators

For queries that are more flexible than precise matches, MongoDB has a variety of comparison operators:

  • $lt: Less than (<).
  • $lte: Less than or equal to (<=).
  • $gt: Greater than (>).
  • $gte: Greater than or equal to (>=).
  • $ne: Not equal to (!=).

These operators can be combined to define ranges:

Example:

db.mycol.find({ "likes": { $lt: 50 } }) // Finds documents with 'likes' less than 50 
db.users.find({ "age": { $gte: 18, $lte: 30 } }) // Finds users between 18 and 30 (inclusive) 

Logical OR Conditions

The $or operator is used to query documents when at least one of several conditions is true. It accepts a collection of inquiry documents, each of which stands for a condition.

Example:

db.mycol.find({ $or: [{ "by": "tutorials point" }, { "title": "MongoDB Overview" }] }).pretty() // Finds documents by 'tutorials point' OR with title 'MongoDB Overview' [75]

Inclusion () and Exclusion ()

  • $in: Accepts an array of potential values and is used to query for a range of values for a single key.
  • $nin: The reverse of $in, it returns documents whose value in the designated field does not satisfy any of the array’s requirements.

Examples:

db.raffle.find({ "ticket_no": { $in: [96, 97] } }) // Finds documents with any of the specified ticket numbers 
db.products.find({ 'details.color': { $nin: ["black", "blue"] } }) // Finds products that are neither black nor blue 

Field Existence ()

The $exists operator queries for documents with or without a specified field.

Examples:

db.media.find({ "Author": { $exists: true } }) // Finds documents with an "Author" key 
db.products.find({ 'details.color': { $exists: false } }) // Finds products where the 'details.color' field does not exist 

Dot Notation for Embedded Documents and Arrays

Dot notation (.) allows MongoDB’s query engine to “reach into” nested objects and match against array elements.

Examples:

db.media.find({ "Tracklist.Title": "In Bloom" }) // Finds documents where an embedded document in 'Tracklist' has 'Title' as "In Bloom" 
db.products.find({ 'details.manufacturer': "Acme" }) // Finds products manufactured by "Acme" within the 'details' embedded document 
db.products.find({ 'tags.0': "soil" }) // Finds products where the first tag ('tags.0') is "soil" 

for Array Elements

Use $elemMatch when you need to define more than one criterion for an array’s elements and all of the conditions must be applicable to the same embedded document in the array.

Example:

db.media.find({ Tracklist: { "$elemMatch": { Title: "Smells Like Teen Spirit", Track: "1" } } }) // Finds documents where a single element in 'Tracklist' matches both title and track 

Operator (JavaScript Expression)

You can pass a JavaScript expression to the query using the $where operator for sophisticated queries that are not amenable to ordinary query operators. However, because $where queries require converting BSON documents to JavaScript objects and prohibit index usage, they are typically slower.

Example:

db.reviews.find({ '$where': "function() { return this.helpful_votes > 3; }" }) 

Projections: Limiting Fields in Results

All fields in all matching documents are returned by default when using find(). You can use a projection as the second optional input to find() to lower processing demands and network cost. You can select which fields to hide (exclusion) or which to return (inclusion) using projections.

  • Inclusion: Enter the name of the field and set its value to either true or 1 For instance:
  • Exclusion: Enter a value of 0 or false for the field name. For instance:
  • _id Field: Despite not being specifically requested in an inclusion projection, the _id field is unique and always appears in the results by default. You must specifically set the _id field to 0 in order to silence it. For instance:
  • Mixing Inclusion and Exclusion: Unless the _id field is specifically excluded in an otherwise inclusive projection, you are generally not allowed to combine inclusion and exclusion assertions in a single projection.
  • $slice Operator in Projections: The $slice operator can return a subset of array elements for fields that contain arrays. For instance:
  • Keep in mind that unless specifically omitted, additional non-array fields in the document are still returned when $slice is utilised.

You may effectively extract the exact data you require from your MongoDB collections by becoming proficient in these query strategies.

Index