In this tutorial, We are going to learn how to Read and Delete MongoDB Documents . We have been already using read operations in our queries to validate our results. Now we are going to see some advanced operations along with the normal read query.

Reading MongoDB documents

We have been using find query to read MongoDB documents in our previous tutorials. Find query returns the cursor to document and we can iterate over cursor to fetch more records. By default, find query returns first 20 records.

We can pass different operators we have learned in previous tutorials MongoDB Operators part I and MongoDB Operators part II to find query to filter out documents.

Now consider we have a lot of data in each document and we want to see only a few fields from that document. We can project values that we want to see in find query. By default, find query projects all the values. We can pass projection as shown in the following query.

In the above query, we have passed value 1 for fields that we want to project. By default, all MongoDB documents show id field. We can use 0 with id field if we want not to show id field with the document.

We can use the limit operator to control how many results that query returns after execution. In the following query, we are limiting results to 5.

Now, we have seen many queries for MongoDB. We can understand the basic format for queries. It has four parts – collection, query criteria, projection and cursor modifier. We can see the same in the following image.Reading Query

Delete MongoDB document

We can use deleteOne and deleteMany queries to delete documents from MongoDB.

We can see in above query that we have deleted 40 records with deleteMany.

Conclusion

In the last few tutorials, we have learned the basics of MongoDB and understand Create, Update, Read and Delete operations. We have also seen MongoDB operators which we can use while querying. Next, we are going to see how to access MongoDB using Python and Java. See you in next tutorial 🙂

I am passionate about data analytics, machine learning, and artificial intelligence. Recently I have started blogging about my experience while learning these exciting technologies.

Leave a Reply

Close Menu