MongoDB

MongoDB close() and isClosed() Example

Hello readers, these days to increase the system capacity it is important to instruct the Mongo database to close a connection and free the associated database resources. In Mongo world, it is pretty straightforward and in this tutorial, we will see the cursor.close() and cursor.isClosed() methods available in the Mongo database. Let’s study in brief the usage of each method.

1. Introduction

If you have installed the MongoDB application (version 3.6) on Windows or Ubuntu operating system and you wish to learn the cursor.close() and cursor.isClosed() methods then follow the below steps. It is very simple. But before moving further let’s take a look at the Mongo database and its features.

1.1 What is MongoDB?

  • MongoDB is a high-performance NoSQL database where each database has collections which in turn has documents. Each document has a different number of fields, size, content, and is stored in a JSON-like format (i.e. Binary JSON (BSN)
  • The documents in MongoDB doesn’t need to have a schema defined beforehand. Instead, the fields (i.e. records) can be created on the go
  • Data model available within the MongoDB allows developers to represent the hierarchical relationships, store arrays, and other more complex structures easily
  • This NoSQL solution often comes with embedding, auto-sharding, and onboard replication for better scalability and high availability

1.1.1 Why MongoDB?

  • As a NoSQL type database, MongoDB stores the data in the form of a document. Thus, MongoDB offers more flexibility
  • This database supports search by field-name, range queries, and the regular expressions. It often provides queries to return the particular fields inside the documents
  • MongoDB offers indexes to improve the search performance within the NoSQL database
  • To offer horizontal scalability, MongoDB uses sharding by splitting the data across the many MongoDB occurrences
  • Replication: MongoDB can give high availability with the replica sets

1.2 What is a Cursor in MongoDB?

In Mongo world, a cursor is an object that allows developers to iterate through the documents of a Mongo collection. The behavior of cursor allows an automatic iteration across the results of the query; however, developers can explicitly go through the items returned in the cursor object. The below diagram lists 4 documents where the Mongo cursor will point to the first document and then iterate through all the other documents of a collection.

Fig. 1: Pictorial representation of a Cursor in Mongo collection
Fig. 1: Pictorial representation of a Cursor in Mongo collection

1.2.1 Why Cursor in MongoDB?

Cursor offers:

  • A true snapshot of a system i.e. it returns the data in batches and increases the database performance
  • It saves system memory by allowing batch inserts and updates
  • Intelligibility and Clarity on the ad-hoc and complex queries of the sequential nature having large result sets and low consistency requirements
  • Openness to work on small batches of data as developers don’t need to wait for the processing and download of the complete record-set

Now, let’s move further and understand how to handle the cursor.close() and cursor.isClosed() methods provided by the Mongo database.

1.3 close() method in the Mongo database

In the Mongo universe, the close() method instructs the server to close a cursor and free the associated server resources. The server will automatically close the cursors that have no remaining results and the cursors that have been idle for a time. Here is what the query syntax will look like.

Mongo database close() Syntax

> db.collection_name.find(<query>).close()

where:

  • The query is the query string on which the documents are retrieved from the collection

1.4 isClosed() method in the Mongo database

In the Mongo universe, the isClosed() method returns true if the server has closed the cursor. A closed cursor may still have documents remaining in the last received batch. Developers can use the cursor.isExhausted() or the cursor.hasNext() methods to check if the cursor is fully exhausted or not. Do note, the official documentation of this method doesn’t provide any query syntax for this method.

1.5 Code Snippet

Let’s understand the implementation of these methods with the help of a sample code snippet.

var Db = require('mongodb').Db,
    MongoClient = require('mongodb').MongoClient,
    Server = require('mongodb').Server,
    ReplSetServers = require('mongodb').ReplSetServers,
    ObjectID = require('mongodb').ObjectID,
    Binary = require('mongodb').Binary,
    GridStore = require('mongodb').GridStore,
    Grid = require('mongodb').Grid,
    Code = require('mongodb').Code,
    BSON = require('mongodb').pure().BSON;

  // Set up the connection to the local db
  var mongoclient = new MongoClient(new Server("home.mongolab.com", 27017), {native_parser: true});

  // Open the connection to the server
  mongoclient.open(function(err, mongoclient) {

    // Get the first db and do an update document on it
    var db = mongoclient.db("warehouse");
    db.collection('editors').update({a:1}, {b:1}, {upsert:true}, function(err, result) {
    	
      // Get another db and do an update document on it
      var db2 = mongoclient.db("warehouse2");
      db2.collection('editors2').update({a:1}, {b:1}, {upsert:true}, function(err, result) {
    	  
        // Close the connection
        mongoclient.close();
      });
    });
  });

That’s all for this post. Happy Learning!!

2. Conclusion

In this tutorial, we learned about the cursor.close() and cursor.isClosed() methods of the Mongo database. Developers can download the sample commands in the Downloads section.

3. Download the Eclipse Project

This was an example of the cursor.close() and cursor.isClosed() methods available in the Mongo database.

Download
You can download the full source code of this example here: Code Snippet

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button