Junior — Middle
What methods can be used to improve efficiency when working with large collections in MongoDB?
sobes.tech AI
Answer from AI
To improve efficiency when working with large collections in MongoDB, the following methods can be used:
- Indexing: creating appropriate indexes to speed up queries.
- Aggregation: using aggregate functions and pipelines to process data on the database side.
- Sharding: distributing the collection across multiple servers for scaling.
- Projection: selecting only necessary fields in queries to reduce the amount of data transferred.
- Pagination: breaking results into pages to handle smaller data volumes at a time.
Example of creating an index in Node.js using the MongoDB driver:
const { MongoClient } = require('mongodb');
async function createIndex() {
const client = new MongoClient('mongodb://localhost:27017');
await client.connect();
const db = client.db('mydb');
const collection = db.collection('largeCollection');
// Create an index on the 'userId' field
await collection.createIndex({ userId: 1 });
await client.close();
}
createIndex();