CRUD Operations in MongoDB: Tutorial with Examples
By Kechit Goyal
Updated on Nov 19, 2024 | 8 min read | 9.11K+ views
Share:
For working professionals
For fresh graduates
More
By Kechit Goyal
Updated on Nov 19, 2024 | 8 min read | 9.11K+ 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.
Popular Data Science Programs
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.
Data Science Courses to upskill
Explore Data Science Courses for Career Progression
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.
Subscribe to upGrad's Newsletter
Join thousands of learners who receive useful tips
The advantages of NoSQL databases become apparent when there is a large quantity of unstructured data. When you are not sure about the relationships within the data, such databases offer much greater flexibility. This is because, unlike SQL-based databases, which store data in relational tables, NoSQL databases are document-oriented. The structure is comparable to a file-folder arrangement, which allows them to assemble related information without necessarily categorizing it. NoSQL databases are also relatively easier to scale up, which means it is easy to increase the available storage by adding extra servers. This process is popularly referred to as “Sharding”.
As companies grow in size and further digitize their various processes, the demand for database developers to categorize and classify data has skyrocketed. Several companies have turned, or are planning to shift to NoSQL technologies for this. It is advisable to get a general grasp on the various technologies in this field instead of focusing exclusively on one. Hadoop, Cassandra, and Couchbase are some notable players. Salaries in this area are also quite generous, with developers making INR 4,15,000 per annum on average. However, depending on location, company, and experience, salaries may reach as high as INR 7,80,000 per annum.
Based on their data models, NoSQL databases can be classified into several subtypes. The key-value store model is the least complex of these. It uses indexed key-value couples without employing any particular schema. Some examples are Azure and Cassandra. The column-store model, as its name suggests, stores data in columns instead of rows. This allows for higher scalability and faster performance. Then there is the Document database which enhances the key-value model, by giving each document its own designated key. It greatly simplifies storage, retrieval, and management. The graph model is capable of highly complex data representation. A lot of data is interconnected and represented as a graph.
95 articles published
Kechit Goyal is a Technology Leader at Azent Overseas Education with a background in software development and leadership in fast-paced startups. He holds a B.Tech in Computer Science from the Indian I...
Speak with Data Science Expert
By submitting, I accept the T&C and
Privacy Policy
Start Your Career in Data Science Today
Top Resources