Read concern levels tell MongoDB how fresh or safe the data you read should be. They help you decide if you want the newest data or data confirmed by many servers.
0
0
Read concern levels (local, majority, snapshot) in MongoDB
Introduction
When you want to read the most recent data even if it is not confirmed by other servers.
When you want to read data that is confirmed by most servers to avoid reading uncommitted changes.
When you want to read a consistent snapshot of data at a specific point in time during a transaction.
When you want to avoid reading data that might be rolled back in case of failures.
When you want to balance between speed and data accuracy depending on your application needs.
Syntax
MongoDB
db.collection.find().readConcern('level') // where 'level' can be 'local', 'majority', or 'snapshot'
local returns the most recent data on the node, even if not confirmed by others.
majority returns data confirmed by most nodes, ensuring durability.
snapshot provides a consistent view of data during a transaction.
Examples
Reads the most recent data from the node, fast but might not be confirmed by others.
MongoDB
db.orders.find().readConcern('local')Reads data confirmed by most nodes, safer but might be slightly older.
MongoDB
db.orders.find().readConcern('majority')Reads a consistent snapshot of data inside a transaction.
MongoDB
session = db.getMongo().startSession({readConcern: {level: 'snapshot'}})
session.startTransaction()
session.getDatabase('shop').orders.find().toArray()
session.commitTransaction()
session.endSession()Sample Program
This example inserts two orders and reads them twice: once with 'local' and once with 'majority' read concern.
MongoDB
use shop // Insert sample data db.orders.insertMany([ {item: 'apple', qty: 5}, {item: 'banana', qty: 10} ]) // Read with local read concern print('Local read concern:') var localData = db.orders.find().readConcern('local').toArray() printjson(localData) // Read with majority read concern print('Majority read concern:') var majorityData = db.orders.find().readConcern('majority').toArray() printjson(majorityData)
OutputSuccess
Important Notes
Use local for fastest reads when you don't mind reading unconfirmed data.
majority is safer for critical data because it reads data confirmed by most servers.
snapshot is only available inside transactions and gives a consistent view of data.
Summary
Read concern controls how fresh and safe your read data is.
local is fastest but less safe, majority is safer but might be slower.
snapshot is for consistent reads inside transactions.