How to Work with MongoDB Queries
MongoDB is not a traditional relational database management system. This is reflected in many aspects: the principles of database design, the format of stored data, the approach to scaling, and the query language.
The primary language for creating queries in relational databases is SQL. However, MongoDB uses its own syntax for queries. In this guide, we’ll discuss how to create queries and which commands are used.
Structure of MongoDB
A MongoDB database consists of collections similar to tables in relational databases. Each collection has its own unique name. Unlike table-based databases, collections do not have a strict data structure with a fixed number of columns and data types.
Collections store documents, which are objects that resemble JSON format. An example of an employee document might look like this:
{
"name": "Mary",
"surname": "Jameson",
"age": 27,
"salary": "100000",
"department": "marketing",
"date of birth": "15.02.1997"
}
Data in documents can be represented in various data types. In this example, all the data is described as strings.
Database and Collection-Level Queries
We will be writing and composing queries in MongoDB Compass. For more details on installing MongoDB on Ubuntu, refer to our tutorial. After installation, three databases will be available on the local server:
To display them, we use the show databases command:
show databases# Output:
admin 40.00 KiB
config 60.00 KiB
local 40.00 KiB
A shorter version, show dbs, can also be used:
show dbs# Output:
admin 40.00 KiB
config 60.00 KiB
local 40.00 KiB
To work with a specific database, use the use command:
use testdb
Output:
'switched to db testdb'
The testdb database does not exist on our server. If the terminal cannot find the specified database when executing the use command, it will create a new one with that name.
Use the db.createCollection("collection_name") command to create collections. Let’s create a collection in the testdb database:
db.createCollection('cloud'){ ok: 1 }
To list collections:
show collectionscloud
To delete a collection, use the drop() command:
db.cloud.drop()true
List collections again to confirm deletion:
show collections
To delete the entire database while working with it, use the db.dropDatabase() command:
db.dropDatabase()
Output:
{ ok: 1, dropped: 'testdb' }
Adding and Deleting Documents
Let’s restore the database and create a collection in it:
use testdb# Output:'switched to db testdb'
db.createCollection('employees')# Output:{ ok: 1 }
Then, we’ll add the first document:
db.employees.insert({
name: "Mary",
surname: "Jameson",
age: 27,
salary: 100000,
department: "marketing",
date_of_birth: "15.02.1997"
})
Output:
'DeprecationWarning: Collection.insert() is deprecated. Use insertOne, insertMany, or bulkWrite.'{ acknowledged: true, insertedIds: { '0': ObjectId("637c9cbd7025c2523a76fe64") } }
After executing insert, the terminal suggests using the insertOne, insertMany, or bulkWrite methods to optimize queries, as insert is now deprecated.
insertOne - Adding a Single Document
The insertOne method adds one document to the collection:
db.employees.insertOne({
name: "James",
surname: "Johns",
age: 37,
salary: 150000,
department: "QA",
date_of_birth: "12.06.1987"
})
Output:
{ acknowledged: true, insertedId: ObjectId("637ca6127025c2523a76fe65") }
insertMany - Adding Multiple Documents
The insertMany method adds an array of documents to the collection:
db.employees.insertMany(
[{
name: "Andrew",
surname: "Stuart",
age: 21,
salary: 12000,
department: "Tech Support",
date_of_birth: "15.10.2003"
},
{
name: "Natalie",
surname: "Richardson",
age: 45,
salary: 200000,
department: "HR",
date_of_birth: "6.05.1979"
}]
)
Output:
{ acknowledged: true,
insertedIds: {
'0': ObjectId("637ca7817025c2523a76fe66"),
'1': ObjectId("637ca7817025c2523a76fe67")
}
}
bulkWrite - Performing Multiple Operations
The bulkWrite method allows you to perform multiple operations, including inserting, deleting, and updating documents:
db.employees.bulkWrite([{
insertOne: {
document: {
name: "Michael",
surname: "Smith",
age: 32,
salary: 20000,
department: "Tech Support",
date_of_birth: "10.01.1992"
}
}
}])
Output:
{ acknowledged: true,
insertedCount: 1,
insertedIds: { '0': ObjectId("637cafaa7025c2523a76fe68") },
matchedCount: 0,
modifiedCount: 0,
deletedCount: 0,
upsertedCount: 0,
upsertedIds: {} }
Using these methods—insertOne, insertMany, and bulkWrite—can improve efficiency and provide more control over document management in MongoDB.
Document Search
The find() query is MongoDB's equivalent of SQL's SELECT. This query searches and displays documents in a collection. To start, let’s output all documents in the employees collection:
db.employees.find()
Output:
[
{
"_id": ObjectId("637c9cbd7025c2523a76fe64"),
"name": "Mary",
"surname": "Jameson",
"age": 27,
"salary": 100000,
"department": "marketing",
"date_of_birth": "15.02.1997"
},
{
"_id": ObjectId("637ca6127025c2523a76fe65"),
"name": "James",
"surname": "Johns",
"age": 37,
"salary": 150000,
"department": "QA",
"date_of_birth": "12.06.1987"
},
{
"_id": ObjectId("637ca7817025c2523a76fe66"),
"name": "Andrew",
"surname": "Stuart",
"age": 21,
"salary": 12000,
"department": "Tech Support",
"date_of_birth": "15.10.2003"
},
{
"_id": ObjectId("637ca7817025c2523a76fe67"),
"name": "Natalie",
"surname": "Richardson",
"age": 45,
"salary": 200000,
"department": "HR",
"date_of_birth": "6.05.1979"
}
]
Search by Criteria
To find a document with specific parameters, pass them as arguments to the find() query. For example, let’s find an employee with a salary of 50000:
db.employees.find({ salary: 50000 })
Output:
[]
In this case, no employees have a salary of 50000, so the output is empty.
If there are multiple parameters, list them separated by commas:
db.employees.find({ salary: 12000, name: "Andrew" })
Output:
[
{
"_id": ObjectId("637ca7817025c2523a76fe66"),
"name": "Andrew",
"surname": "Stuart",
"age": 21,
"salary": 12000,
"department": "Tech Support",
"date_of_birth": "15.10.2003"
}
]
Find with OR Condition
To set an OR condition in the MongoDB query, use $or:
db.employees.find({ $or: [{ salary: 50000 }, { name: "Natalie" }] })
Output:
[
{
"_id": ObjectId("637ca7817025c2523a76fe67"),
"name": "Natalie",
"surname": "Richardson",
"age": 45,
"salary": 200000,
"department": "HR",
"date_of_birth": "6.05.1979"
}
]
Search with Comparison
The following comparison operators are used:
$lt — less than
$lte — less than or equal to
$gt — greater than
$gte — greater than or equal to
$ne — not equal
For example, let’s find employees with a salary greater than 100000 and under the age of 30:
db.employees.find({ salary: { $gte: 100000 }, age: { $lt: 30 } })
Output:
[
{
"_id": ObjectId("637c9cbd7025c2523a76fe64"),
"name": "Mary",
"surname": "Jameson",
"age": 27,
"salary": 100000,
"department": "marketing",
"date_of_birth": "15.02.1997"
}
]
Sorting
The sort() method sorts documents based on a given parameter and takes a number: 1 for ascending order or -1 for descending order. Let’s sort employees by age:
db.employees.find().sort({ age: 1 })
Output:
[
{
"_id": ObjectId("637ca7817025c2523a76fe66"),
"name": "Andrew",
"surname": "Stuart",
"age": 21,
"salary": 12000,
"department": "Tech Support",
"date_of_birth": "15.10.2003"
},
{
"_id": ObjectId("637c9cbd7025c2523a76fe64"),
"name": "Mary",
"surname": "Jameson",
"age": 27,
"salary": 100000,
"department": "marketing",
"date_of_birth": "15.02.1997"
},
{
"_id": ObjectId("637ca6127025c2523a76fe65"),
"name": "James",
"surname": "Johns",
"age": 37,
"salary": 150000,
"department": "QA",
"date_of_birth": "12.06.1987"
},
{
"_id": ObjectId("637ca7817025c2523a76fe67"),
"name": "Natalie",
"surname": "Richardson",
"age": 45,
"salary": 200000,
"department": "HR",
"date_of_birth": "6.05.1979"
}
]
Limiting Results
To limit the number of documents returned, use the limit() method:
db.employees.find().sort({ age: 1 }).limit(2)
Output:
[
{
"_id": ObjectId("637ca7817025c2523a76fe66"),
"name": "Andrew",
"surname": "Stuart",
"age": 21,
"salary": 12000,
"department": "Tech Support",
"date_of_birth": "15.10.2003"
},
{
"_id": ObjectId("637c9cbd7025c2523a76fe64"),
"name": "Mary",
"surname": "Jameson",
"age": 27,
"salary": 100000,
"department": "marketing",
"date_of_birth": "15.02.1997"
}
]
Document Updates
To update documents in a MongoDB database, use a query with the update() command. It takes two parameters: the first specifies which documents to update, and the second indicates which fields to change and their new values. Here’s an example:
db.employees.update({ name: 'Mary' },
{
$set: {
name: 'Anna',
age: 51,
date_of_birth: '15.11.1972'
}
})
Then, to verify the update, we can search for documents with the new name:
db.employees.find({ name: 'Anna' })
Output:
[
{
"_id": ObjectId("637c9cbd7025c2523a76fe64"),
"name": "Anna",
"surname": "Jameson",
"age": 51,
"salary": 100000,
"department": "marketing",
"date_of_birth": "15.11.1972"
}
]
Renaming Fields
To rename fields, use the $rename operator. In this case, let’s rename name to first_name:
db.employees.updateMany({}, {
$rename: {
name: 'first_name'
}
})
Now, all documents with the name field will have it replaced by first_name.
Document Deletion
MongoDB provides two functions for deleting documents: deleteOne() and deleteMany().
deleteOne()
The deleteOne() function deletes the first document that matches the criteria. For example, let’s delete an employee named "Natalie":
db.employees.deleteOne({ first_name: 'Natalie' })
Output:
{ acknowledged: true, deletedCount: 1 }
deleteMany()
The deleteMany() function deletes all documents that match the criteria. Let’s delete all employees in the Tech Support department:
db.employees.deleteMany({ department: 'Tech Support' })
Output:
{ acknowledged: true, deletedCount: 2 }
After these deletions, only two documents should remain in the employees collection. Let’s check:
db.employees.find()
Final Output:
[
{
"_id": ObjectId("637c9cbd7025c2523a76fe64"),
"first_name": "Anna",
"surname": "Jameson",
"age": 51,
"salary": 100000,
"department": "marketing",
"date_of_birth": "15.11.1972"
},
{
"_id": ObjectId("637ca6127025c2523a76fe65"),
"first_name": "James",
"surname": "Johns",
"age": 37,
"salary": 150000,
"department": "QA",
"date_of_birth": "12.06.1987"
}
]
In summary, these operations—update, $rename, deleteOne, and deleteMany—allow you to manage document updates and deletions efficiently in MongoDB.
MongoDB Query Optimization
To improve the speed of your queries, consider the following tips:
Create indexes for frequently used queries.
Limit the number of returned documents. MongoDB retrieves all matching documents by default, so use the limit() method if you only need part of the result.
Return only necessary fields from documents. You can enhance query performance by specifying only the required fields in the search result.
Use more "selective" queries. For example, checking by _id will return no more than one document. Aim to use parameters in MongoDB queries that most accurately describe the documents you need.
Conclusion
MongoDB provides a straightforward query syntax that enables efficient document management within databases. In this material, we covered basic MongoDB queries that encompass primary document management tasks.
We used a database hosted locally, but you can also host a database in the cloud using Hostman Managed Databases. Cloud databases are easier to administer and scale and can be managed and created using a web interface.
02 November 2024 · 10 min to read