MongoDB

MongoDB hint() Example

Hello readers, in this tutorial, we will see the hint() method available in the Mongo database.

1. Introduction

If you have installed the MongoDB application (version 3.6) on Windows or Ubuntu operating system and you wish to learn the hint() method then follow the below steps. It is very simple, but before moving further let’s take a look at the Mongo database and its characteristics.

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

2. MongoDB hint() Example

In this tutorial, we will learn how to handle the hint() method provided by the Mongo database.

2.1 hint() method in the Mongo database

In the Mongo universe, the hint() method influences the Mongo database to override the default index and the query optimization process. The cursor.hint() method has the following prototype form:

Mongo database ‘hint()’ Syntax

> db.collection_name.find().hint(<index>)

Where:

  • The index forces the Mongo database to use a specific index for a query. Developers can specify this index either by the index-name or by the index-specification-document

Do remember:

  • To force the collection scans, developers can specify the { $natural: integer_value } input argument to the hint() method. This integer_value accepts 1 to do a forward collection scan or -1 to do a reverse collection scan
  • Developers cannot use the hint() method if the Mongo query includes a $text expression

2.2 Practical usage

Let’s understand the implementation of this method with the help of the sample snippets.

2.2.1 Start MongoDB

Start a standalone mongod instance as shown below.

Fig. 2: Start Mongo instance
Fig. 2: Start Mongo instance

2.2.2 Connect to the Mongo Instance

Connect with the mongo shell to make a connection with the MongoDB instance on the port 27017 as shown below.

Fig. 3: Connect to Mongo database
Fig. 3: Connect to Mongo database

2.2.3 Create Mongo database and collection

To begin with the implementation, we will need to create a sample database and collection. The below script creates a database called places with a collection of restaurants. Open the Mongo terminal and execute the script.

Database & Collection creation script

> use places

> db.restaurants.insertMany( [
	{"address": {"building": "1007", "coord": [-73.856077, 40.848447], "street": "Morris Park Ave", "zipcode": "10462"}, "borough": "Bronx", "cuisine": "Bakery", "grades": [{"date": {"$date": 1393804800000}, "grade": "A", "score": 2}, {"date": {"$date": 1378857600000}, "grade": "A", "score": 6}, {"date": {"$date": 1358985600000}, "grade": "A", "score": 10}, {"date": {"$date": 1322006400000}, "grade": "A", "score": 9}, {"date": {"$date": 1299715200000}, "grade": "B", "score": 14}], "name": "Morris Park Bake Shop", "restaurant_id": "30075445"},
	{"address": {"building": "469", "coord": [-73.961704, 40.662942], "street": "Flatbush Avenue", "zipcode": "11225"}, "borough": "Brooklyn", "cuisine": "Hamburgers", "grades": [{"date": {"$date": 1419897600000}, "grade": "A", "score": 8}, {"date": {"$date": 1404172800000}, "grade": "B", "score": 23}, {"date": {"$date": 1367280000000}, "grade": "A", "score": 12}, {"date": {"$date": 1336435200000}, "grade": "A", "score": 12}], "name": "Wendy'S", "restaurant_id": "30112340"},
	{"address": {"building": "351", "coord": [-73.98513559999999, 40.7676919], "street": "West   57 Street", "zipcode": "10019"}, "borough": "Manhattan", "cuisine": "Irish", "grades": [{"date": {"$date": 1409961600000}, "grade": "A", "score": 2}, {"date": {"$date": 1374451200000}, "grade": "A", "score": 11}, {"date": {"$date": 1343692800000}, "grade": "A", "score": 12}, {"date": {"$date": 1325116800000}, "grade": "A", "score": 12}], "name": "Dj Reynolds Pub And Restaurant", "restaurant_id": "30191841"},
	{"address": {"building": "2780", "coord": [-73.98241999999999, 40.579505], "street": "Stillwell Avenue", "zipcode": "11224"}, "borough": "Brooklyn", "cuisine": "American ", "grades": [{"date": {"$date": 1402358400000}, "grade": "A", "score": 5}, {"date": {"$date": 1370390400000}, "grade": "A", "score": 7}, {"date": {"$date": 1334275200000}, "grade": "A", "score": 12}, {"date": {"$date": 1318377600000}, "grade": "A", "score": 12}], "name": "Riviera Caterer", "restaurant_id": "40356018"},
	{"address": {"building": "97-22", "coord": [-73.8601152, 40.7311739], "street": "63 Road", "zipcode": "11374"}, "borough": "Queens", "cuisine": "Jewish/Kosher", "grades": [{"date": {"$date": 1416787200000}, "grade": "Z", "score": 20}, {"date": {"$date": 1358380800000}, "grade": "A", "score": 13}, {"date": {"$date": 1343865600000}, "grade": "A", "score": 13}, {"date": {"$date": 1323907200000}, "grade": "B", "score": 25}], "name": "Tov Kosher Kitchen", "restaurant_id": "40356068"},
	{"address": {"building": "8825", "coord": [-73.8803827, 40.7643124], "street": "Astoria Boulevard", "zipcode": "11369"}, "borough": "Queens", "cuisine": "American ", "grades": [{"date": {"$date": 1416009600000}, "grade": "Z", "score": 38}, {"date": {"$date": 1398988800000}, "grade": "A", "score": 10}, {"date": {"$date": 1362182400000}, "grade": "A", "score": 7}, {"date": {"$date": 1328832000000}, "grade": "A", "score": 13}], "name": "Brunos On The Boulevard", "restaurant_id": "40356151"},
	{"address": {"building": "7114", "coord": [-73.9068506, 40.6199034], "street": "Avenue U", "zipcode": "11234"}, "borough": "Brooklyn", "cuisine": "Delicatessen", "grades": [{"date": {"$date": 1401321600000}, "grade": "A", "score": 10}, {"date": {"$date": 1389657600000}, "grade": "A", "score": 10}, {"date": {"$date": 1375488000000}, "grade": "A", "score": 8}, {"date": {"$date": 1342569600000}, "grade": "A", "score": 10}, {"date": {"$date": 1331251200000}, "grade": "A", "score": 13}, {"date": {"$date": 1318550400000}, "grade": "A", "score": 9}], "name": "Wilken'S Fine Food", "restaurant_id": "40356483"},
	{"address": {"building": "6409", "coord": [-74.00528899999999, 40.628886], "street": "11 Avenue", "zipcode": "11219"}, "borough": "Brooklyn", "cuisine": "American ", "grades": [{"date": {"$date": 1405641600000}, "grade": "A", "score": 12}, {"date": {"$date": 1375142400000}, "grade": "A", "score": 12}, {"date": {"$date": 1360713600000}, "grade": "A", "score": 11}, {"date": {"$date": 1345075200000}, "grade": "A", "score": 2}, {"date": {"$date": 1313539200000}, "grade": "A", "score": 11}], "name": "Regina Caterers", "restaurant_id": "40356649"}
] )

The script gives the below output.

Fig. 4: Database & Collection creation
Fig. 4: Database & Collection creation

2.2.4 Check Mongo database and collection

If the script works well, the database and the collection will be shown in the Mongo Workbench. Using the db.collection_name.find() or the db.collection_name.find().pretty() command the documents of a collection will be shown as below.

Fig. 5: Mongo database & collection
Fig. 5: Mongo database & collection

2.2.5 Implementation of ‘hint()’ method

Now, go back to the Mongo shell and use the hint(<index>) method to force the Mongo database to use a specific index for the query. To use this cursor function, we will need to make sure that an index already exists in the restaurants collection as shown below.

Fig. 6: Get Indexes for the 'restaurants' collection
Fig. 6: Get Indexes for the ‘restaurants’ collection

The below example returns all documents in the collection named restaurants using the index on the cuisine field.

Query 1

> db.restaurants.find().hint( { cuisine: 1 } )

This command will return all the documents using the index on the cuisine field.

Fig. 7: Mongo database hint() method
Fig. 7: Mongo database hint() method

Let’s say developers want to return the documents by specifying the index-name. They can do this by simply appending the index-name in the hint() method. Let’s understand this with the help of an example.

Query 1(a)

> db.restaurants.find().hint( "cuisine_1" )

Do remember, this method will return an exception if the hint() method query includes a $text query expression. Let’s understand this with the help of an example.

Exception Trace

> db.restaurants.find( { $text: { $search: "American" } } ).hint()

Error: error: {
        "ok" : 0,
        "errmsg" : "hint must be either a string or nested object",
        "code" : 9,
        "codeName" : "FailedToParse"

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

3. Conclusion

In this tutorial, we learned about the hint() method of the Mongo database. Developers can download the sample commands in the Downloads section.

4. Download the Eclipse Project

This was an example of the hint() method available in the Mongo database.

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

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
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button