https://static1.makeuseofimages.com/wordpress/wp-content/uploads/2023/08/mongodb-queries-you-must-know.jpg
MongoDB is one of the most desired and admired NoSQL databases for professional development. Its flexibility, scalability, and ability to handle large volumes of data make it a top choice for modern applications. If you want to master MongoDB’s regular queries and operations, you’re in the right place.
Whether you’re looking to efficiently retrieve and manipulate data, implement robust data models, or build responsive applications, acquiring a deep understanding of common MongoDB queries and operations will undoubtedly enhance your skills.
1. Create or Switch Databases
Creating a database locally via the MongoDB Shell is straightforward, especially if you’ve set up a remote cluster. You can create a new database in MongoDB with the use command:
use db_name
While the above command creates a new database, you can use it to switch to an existing database without creating a new one from scratch.
2. Drop Database
First, switch to the database you want to drop using the use command as done previously. Then drop the database using the dropDatabase() command:
use db_name
db.dropDatabase()
3. Create a Collection
To create a collection, switch to the target database. Use the createCollection() keyword to make a new MongoDB collection:
db.createCollection("collection_name")
Replace collection_name with your chosen collection name.
4. Insert Document Into a Collection
While sending data to a collection, you can insert a single document or an array of documents.
To insert a single document:
db.collection_name.insertOne({"Name":"Idowu", "Likes":"Chess"})
You can also use the above method to insert an array of documents with one ID:
db.collection_name.insertOne([{"Name":"Idowu", "Likes":"Chess"}, {"Language": "Mongo", "is_admin": true}])
To insert many documents at once, with each having separate IDs, use the insertMany keyword:
db.collection_name.insertMany([{"Name":"Idowu", "Likes":"Chess"}, {"Name": "Paul", "Likes": "Wordle"}])
5. Get All Documents From a Collection
You can query all documents from a collection using the find() keyword:
db.collection_name.find()
The above returns all the documents inside the specified collection:
You can also limit the returned data to a specific number. For instance, you can use the following command to get only the first two documents:
db.collection_name.find().limit(2)
6. Filter Documents in a Collection
There are many ways to filter documents in MongoDB. Consider the following data, for instance:
If querying only a specific field in a document, use the find method:
db.collection_name.find({"Likes":"Wordle"}, {"_id":0, "Name":1})
The above returns all documents where the value of Likes is Wordle. It only outputs the names and ignores the document ID.
You can also filter a collection by a numerical factor. Say you want to get the names of all users older than 21, use the $gt operator:
db.collection_name.find({"Likes":"Chess", "Age":{"$gt":21}}, {"_id":0, "Name":1})
The output looks like so:
Try replacing find with findOne to see what happens. However, there are many other filtering keywords:
- $lt: All values less than the specified one.
- $gte: Values equal to or greater than the specified one.
- $lte: Values that are less than or equal to the defined one.
- $eq: Gets all values equal to the specified one.
- $ne: All values not equal to the specified one.
- $in: Use this when querying based on an array. It gets all values matching any of the items in the array. The $nin keyword does the opposite.
7. Sort Queries
Sorting helps arrange the query in a specific order. You can sort in descending or ascending order. Keep in mind that sorting requires a numerical reference.
For instance, to sort in ascending order:
db.collection_name.find({"Likes":"Chess"}).sort({"Age":1})
To sort out the above query in descending order, replace “1” with “-1.”
db.collection_name.find({"Likes":"Chess"}).sort({"Age":-1})
8. Update a Document
MongoDB updates require atomic operators to specify how you want the update done. Here is a list of commonly used atomic operators you can pair with an update query:
- $set: Add a new field or change an existing field.
- $push: Insert a new item into an array. Pair it with the $each operator to insert many items at once.
- $pull: Remove an item from an array. Use it with $in to remove many items at one go.
- $unset: Remove a field from a document.
To update a document and add a new field, for example:
db.collection_name.updateOne({"Name":"Sandy"}, {"$set":{"Name":"James", "email":"example@gmail.com"}})
The above updates the specified document as shown:
Removing the email field is straightforward with the $unset operator:
db.collection_name.updateOne({"Name":"Sandy"}, {"$unset":{"email":"example@gmail.com"}})
Consider the following sample data:
You can insert an item into the existing items array field using the $push operator:
db.collection_name.updateOne({"Name":"Pete"}, {"$push":{"items":"Plantain"}})
Here’s the output:
Use the $each operator to insert many items at once:
db.collection_name.updateOne({"Name":"Pete"}, {"$push":{"items": {"$each":["Almond", "Melon"]}}})
Here’s the output:
As mentioned, the $pull operator removes an item from an array:
db.collection_name.updateOne({"Name":"Pete"}, {"$pull":{"items":"Plantain"}})
The updated data looks like so:
Include the $in keyword to remove many items in an array at one go:
db.collection_name.updateOne({"Name":"Pete"}, {"$pull":{"items": {"$in":["Almond", "Melon"]} }})
9. Delete a Document or a Field
The deleteOne or deleteMany keyword trashes a document from a collection. Use deleteOne to remove a document based on a specified field:
db.collection_name.deleteOne({"Name":"IDNoble"})
If you want to delete many documents with keys in common, use deleteMany instead. The query below deletes all documents containing Chess as their Likes.
db.collection.deleteMany({"Likes":"Chess"})
10. Indexing Operation
Indexing improves query performance by streamlining the number of documents MongoDB needs to scan. It’s often best to create an index on fields you query more frequently.
MongoDB indexing is similar to how you use indexes to optimize SQL queries. For instance, to create an ascending index on the Name field:
db.collection.createIndex({"Name":1})
To list your indexes:
db.collection.getIndexes()
The above is only a preamble. There are several other methods for creating an index in MongoDB.
11. Aggregation
The aggregation pipeline, an improved version of MapReduce, allows you to run and store complex calculations from inside MongoDB. Unlike MapReduce, which requires writing the map and the reduce functions in separate JavaScript functions, aggregation is straightforward and only uses built-in MongoDB methods.
Consider the following sales data, for example:
Using MongoDB’s aggregation, you can calculate and store the total number of products sold for each category as follows:
db.sales.aggregate([{$group:{"_id":"$Section", "totalSold":{$sum:"$Sold"}}}, {$project:{"_id":0, "totalSold":1, "Section":"$_id"}}])
The above query returns the following:
Master MongoDB Queries
MongoDB offers many querying methods, including features to improve query performance. Regardless of your programming language, the above query structures are rudimentary for interacting with a MongoDB database.
There may be some discrepancies in base syntaxes, though. For example, while some programming languages like Python recognize snake cases, others, including JavaScript, use the camel case. Ensure you research what works for your chosen technology.
MakeUseOf