CRUD operations in MongoDB

Hey, I am Shalini Muskula, an undergrad student learning Web Development. I recently started contributing to Open Source. I will be focusing on Web development and DSA in my blogs.
In this blog I will be covering the CRUD operations on a database in MongoDB with examples.
Instead of records, MongoDB has documents. You have collections instead of tables.
Let us see how to perform CRUD operations in MongoDB.
Use show dbs to show the databases. use databseName opens the database if it already exists else it creates a new database.
You can create a collection by using db.createCollection("Collection Name") . You can use show collections to view the collections in the database.

Create/save documents in a collection
InsertOne: Used to insert a single document into the collection. db.collectionName.insertOne(document)


InsertMany: Used to insert many documents into the collection.
db.collectionName.insertMany([document1, document2])

Finding a document
db.collectionName.findOne() returns the first document in the collection.
db.collectionName.find() returns all the documents in the collection.
Query Operators
$eq - equal to


$gt - greater than
$gte - greater than or equal to
$lt - less than

$in - check if the value is there

$and - and operation between the conditions

The $all operator selects the documents where the value of a field is an array that contains all the specified elements.
$size - checks the size

Update documents of a collection
It can be done using $set operator. updateOne updates the first document in the resulting search of the collection. updateMany updates all the documents matching the search conditions.

other operators:
$set - assign new value and change the existing value.$inc - increment$rename - used to rename the field.$unset - remove any field from the document.
Array update operators$add_to_set - won't add if it is already present.$push - pushes into the set$pop - can remove from beginning/ending$pull - remove using the name$pullAll - removes all
Delete documents of a collection
deleteOne(condition) - used to delete the topmost result
deleteMany(condition) - used to delete the documents that match the condition
Drop database and collection
db.dropDatabase() - used to drop current database
db.collectionName.drop() - used to drop collection
Thank you for reading the blog. I was revising MongoDB and dropped references from my notes. Feel free to comment in case of any suggestions or issues. Feedback is always welcomed!




