0
0
MongoDBquery~30 mins

Read preference for replica sets in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
Read Preference for Replica Sets in MongoDB
📖 Scenario: You are managing a MongoDB database with a replica set. You want to control how your application reads data from the primary and secondary members of the replica set to balance load and ensure data freshness.
🎯 Goal: Build a MongoDB query setup that uses different read preferences to read data from the replica set members.
📋 What You'll Learn
Create a MongoDB collection named products with sample documents.
Set a read preference variable to secondaryPreferred.
Write a query that uses the read preference variable to read documents from the products collection.
Add a final configuration to confirm the read preference is applied.
💡 Why This Matters
🌍 Real World
In real applications, controlling read preference helps balance load between primary and secondary database servers, improving performance and availability.
💼 Career
Database administrators and backend developers often configure read preferences to optimize data reads in distributed MongoDB setups.
Progress0 / 4 steps
1
Create the products collection with sample data
Create a MongoDB collection called products and insert these exact documents: { _id: 1, name: "Pen", price: 1.5 }, { _id: 2, name: "Notebook", price: 3 }, and { _id: 3, name: "Eraser", price: 0.5 }.
MongoDB
Need a hint?

Use db.products.insertMany() with an array of documents.

2
Set the read preference variable
Create a variable called readPref and set it to the string "secondaryPreferred" to specify the read preference.
MongoDB
Need a hint?

Use const readPref = "secondaryPreferred"; to set the variable.

3
Query the products collection using the read preference
Write a query that finds all documents in the products collection using the readPref variable as the read preference option.
MongoDB
Need a hint?

Use db.products.find().readPref(readPref) to apply the read preference.

4
Confirm the read preference is applied
Add a line to assign the read preference readPref to the cursor variable explicitly to confirm the read preference is set.
MongoDB
Need a hint?

Call cursor.readPref() to confirm the read preference is applied.