Retrieving documents from MongoDB collections in Node.js is executed using findOne() to fetch a single matching document or find() to return a query cursor.
flowchart TD
A["collection.find(filter)"] --> B["MongoDB Find Cursor"]
B -->|"cursor.toArray()"| C["Load all documents into JS Array in memory"]
B -->|"for await (const doc of cursor)"| D["Stream documents one-by-one safely"]
import { MongoClient } from 'mongodb';
const uri = 'mongodb://127.0.0.1:27017';
const client = new MongoClient(uri);
async function queryProductsCollection() {
try {
await client.connect();
const db = client.db('kodersolution_no_sql');
const products = db.collection('products');
// 1. findOne matching specific criteria
const singleProduct = await products.findOne({ title: 'Ergonomic Mouse' });
console.log('Single Product Match:', singleProduct);
// 2. find() with Projection (inclusion/exclusion of fields)
const filter = { category: 'Electronics' };
const projectionOptions = {
projection: { title: 1, price: 1, _id: 0 } // Include title & price, exclude _id
};
const cursor = products.find(filter, projectionOptions);
const results = await cursor.toArray();
console.log(`Found ${results.length} Electronics products (Projected Fields):`);
console.log(results);
} catch (err) {
console.error('MongoDB Find Error:', err.message);
} finally {
await client.close();
}
}
queryProductsCollection();
{ projection: { field: 1 } } to fetch only required document fields across the network.for await (const doc of cursor) instead of .toArray() when querying large collections to avoid loading millions of records into Node.js RAM at once.How do you exclude the _id field from query results when using MongoDB projections?
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With