CRUD Operations in MongoDB: Tutorial with Examples
Updated on Nov 19, 2024 | 8 min read | 8.5k views
Share:
For working professionals
For fresh graduates
More
Updated on Nov 19, 2024 | 8 min read | 8.5k views
Share:
With the continuous evolution of the web, we are now seeing how MongoDB and other document object databases are coming up as alternatives to conventional SQL based databases. There are several advantages that these document object databases have over SQL databases, and the most prominent ones out of all these benefits include scalability and agility.
It is important to note that data in MongoDB is stored binary encoded JSON (BSON) documents format. This format may have a requirement of holding arrays of embedded documents or for that matter values. A document forms a record in MongoDB, which is a structure created out of value and field pairs.
Let us now discuss create, update, retrieve, and delete operations or CRUD operations in MongoDB. These functions can be broadly classified as data modification functions in MongoDB. These can only be used for a single collection. Insert is a function in MongoDB that can be used to add data to the database.
How are objects created using MongoDB? MongoDB uses BSON – a binary representation of JSON – for its storage. So, it is quite easy to understand that methods used to perform different operations in the database have something or the other to do with JavaScript. Let us create a user and users’ collection. It is also important to note that tables in SQL are equivalent to collections in MongoDB.
db.users.save({name:”Mike”, job:”doctor”,email:”name@sample.com”})
This example uses MongoDB save() for saving the data to the collection.
For instance, if an ordered list has one insert operation followed by a delete operation followed by two update operations, MongoDB will create three groups to stack these. Group one will consist of one insert operation. The second group will have one delete operation. The third group will put the two update operations together.
The future editions of MongoDB are expected to deal appropriately with this behavior. Each group of ordered bulk lists can’t have more than 1000 operations. In case the number goes beyond that maximum limit, MongoDB creates smaller groups of 1000 operations or less, to adhere to this limit. So if there are 7000 ordered bulk operations, there will be seven groups, each consisting of 1000 bulk operations. To see how grouping and execution are done, first execute the bulk insert command and then use the Bulk.getOperations command. This command can be used to add three documents in order.
Every query in MongoDB is directed at particular documents. MongoDB identifies documents based on the condition defined in a query and then returns those documents to its intended destination. A document retrieval query can have a projection that mentions conditions or criteria that match with the fields of the document that needs to be returned.
Queries can be modified to put skips, limits and sort orders.
Let us now discuss how the equality condition is specified. Use the findOne() command to identify a document’s first record. To display results in the proper format, you can use the pretty method.
Use the db.items.find().pretty() query to identify all the documents listed in a collection and display all of them in a standardized format. You can use an empty query to pick all documents – db.items.find( {} ) – this query has an empty query clause at the end – so it will identify all documents listed in a collection.
Not specifying the find method with a query document and using an empty query will both deliver the same result. So, db.items.find( {} ) and db.items.find() queries are equivalent in terms of the result they are used for.
You can manipulate the query and use the query cursor method while the count method lets you find out the number of documents in a collection that match your query. db.items.count()
You need to use the update() method to update documents in MongoDB. The update method features two important elements – query and update. Query parameter comes first followed by the update parameter. Here is an example
db.users.update({name:”Mike”}, {age: 32})
However, this isn’t the right way to update a value pair, which in this case is age. With this, you will overwrite everything in the document. The only thing that will remain in the age. So when we have to update a single value pair in the entire document, we need to use a few keywords.
db.users.update({name: “Mike”}, { $set: { age: 28}})
This won’t overwrite anything. You would retain all the information the document has. Only the value of age will be updated.
Use the remove method – db.courses.remove() – to remove documents from a collection. This command will remove all the documents from the given collection. What it won’t remove are the indexes and the collection itself. At times, the remove command can take a query as a parameter. If you want to remove documents that match the criteria mentioned in the query, use db.items.remove({“item”: “Pen”) command.
Use the db.items.remove({” item” : “Bag},1) command to remove only one document from a collection. To remove all the documents, collection, and indexes, use the db.courses.drop() command (drop method).
If you are interested to know more about Big Data, check out our Advanced Certificate Programme in Big Data from IIIT Bangalore.
Learn Software Development Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs or Masters Programs to fast-track your career.
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
Start Your Career in Data Science Today
Top Resources