Skip to content

MongoDB - Query Document

Querying is the process of retrieving data from your database. MongoDB provides a rich and powerful query language to find the exact documents you need. This chapter covers the fundamentals of querying, from basic lookups to complex logical conditions.

Let’s start by inserting a realistic dataset into a posts collection. We’ll use modern methods like insertMany and appropriate data types (Number, Boolean, Array, etc.).

db.posts.insertMany([
{
title: "Introduction to MongoDB",
author: "Chris",
tags: ["mongodb", "database", "nosql"],
views: 1500,
isPublished: true,
comments: [
{ user: "Alice", text: "Great overview!" },
{ user: "Bob", text: "Very helpful, thanks." }
]
},
{
title: "Advanced Aggregation",
author: "Sarah",
tags: ["mongodb", "aggregation", "advanced"],
views: 750,
isPublished: true
},
{
title: "Schema Design Best Practices",
author: "Chris",
tags: ["mongodb", "schema", "modeling"],
views: 2200,
isPublished: true
},
{
title: "Upcoming Features",
author: "Chris",
tags: ["mongodb", "future"],
views: 50,
isPublished: false
}
]);

find(query, projection) is the primary method for querying. It returns a cursor, which is a pointer to the result set. findOne(query, projection) is a convenient alternative that returns only the first document that matches the query, or null if no match is found.

// Find all documents in the collection (empty query document)
> db.posts.find({})
// Find the first document written by 'Chris'
> db.posts.findOne({ author: "Chris" })
// Note: mongosh automatically formats the JSON output for readability.
// The legacy .pretty() method still works but is no longer necessary.

To create more specific queries, you use query operators. They are the equivalent of WHERE clauses in SQL.

OperationSyntaxExample (on posts collection)RDBMS Equivalent
Equality{ : }db.posts.find({ author: “Sarah” })WHERE author = ‘Sarah’
Less Than{ : { $lt: } }db.posts.find({ views: { $lt: 1000 } })WHERE views < 1000
Greater Than or Equal{ : { $gte: } }db.posts.find({ views: { $gte: 1500 } })WHERE views >= 1500
Not Equal{ : { $ne: } }db.posts.find({ author: { $ne: “Chris” } })WHERE author != ‘Chris’
Value in Array{ : { $in: [, ] } }db.posts.find({ author: { $in: [“Chris”, “Sarah”] } })WHERE author IN (‘Chris’, ‘Sarah’)
Value Not in Array{ : { $nin: [, ] } }db.posts.find({ tags: { $nin: [“future”, “draft”] } })WHERE tag is not in (‘future’, ‘draft’)

By default, when you provide multiple fields in a query document, MongoDB performs a logical AND. The following query finds posts by ‘Chris’ that are also published.

> db.posts.find({ author: "Chris", isPublished: true })

To find documents that match at least one of several conditions, use the $or operator, which takes an array of query documents.

// Find posts that have less than 100 views OR are not yet published
> db.posts.find({
$or: [
{ views: { $lt: 100 } },
{ isPublished: false }
]
})

The $nor operator finds documents that fail to match all conditions in the array. It means “neither this, nor that”.

// Find posts NOT authored by 'Sarah' AND that do NOT have the 'nosql' tag
> db.posts.find({
$nor: [
{ author: 'Sarah' },
{ tags: 'nosql' }
]
})

To find documents where an array contains a specific element, simply query for that value.

// Find all posts tagged with 'mongodb'
> db.posts.find({ tags: "mongodb" })

Querying Embedded Documents with Dot Notation

Section titled “Querying Embedded Documents with Dot Notation”

Use dot notation to query fields within an embedded document or an array of documents.

// Find posts where a user named 'Alice' has commented
> db.posts.find({ "comments.user": "Alice" })

A simple query like { 'comments.user': 'Alice', 'comments.text': '...' } could match if one comment is by Alice and a different comment has the specified text. To ensure multiple criteria are met by a single element in an array, use $elemMatch.

// Find posts with a comment from 'Bob' that contains the word 'helpful'
// This ensures 'user' and 'text' conditions apply to the same comment object
> db.posts.find({
comments: {
$elemMatch: { user: "Bob", text: /helpful/ }
}
})

Practical Application: Node.js Driver Example

Section titled “Practical Application: Node.js Driver Example”

Here’s how you would perform a query in a typical Node.js application using the official mongodb driver. First, ensure you have the driver installed: npm install mongodb.

const { MongoClient } = require('mongodb');
// Replace with your MongoDB deployment's connection string.
const uri = 'mongodb://localhost:27017';
const client = new MongoClient(uri);
async function run() {
try {
await client.connect();
const database = client.db('yourDbName'); // Replace with your DB name
const posts = database.collection('posts');
// Query for popular, published posts by Chris
const query = {
author: 'Chris',
isPublished: true,
views: { $gte: 1000 }
};
const cursor = posts.find(query);
// Print a message if no documents were found
if ((await posts.countDocuments(query)) === 0) {
console.log("No documents found!");
}
// Print each document
for await (const doc of cursor) {
console.dir(doc);
}
} finally {
// Ensures that the client will close when you finish/error
await client.close();
}
}
run().catch(console.dir);

To understand how MongoDB is executing your query and to identify performance bottlenecks, use the explain() method. This is crucial for checking if your queries are using indexes effectively.

> db.posts.find({ author: 'Chris', views: { $gt: 1000 } }).explain('executionStats')
// Analyze the 'executionStats' in the output.
// A 'winningPlan' that shows 'IXSCAN' (index scan) is much better than 'COLLSCAN' (collection scan).