Inserting and Finding Documents
insertOne, insertMany, find, and projection
Skills taught: mongodb.crud-read
Inserting Documents
MongoDB provides two insert methods: insertOne() for a single document and insertMany() for multiple documents at once. Both return an acknowledgement with the inserted _id(s).
const { MongoClient, ObjectId } = require('mongodb');
const client = new MongoClient('mongodb://localhost:27017');
await client.connect();
const db = client.db('shop');
const products = db.collection('products');
// Insert one document
const r1 = await products.insertOne({
name: 'Wireless Headphones',
price: 2499,
category: 'Electronics',
inStock: true,
tags: ['audio', 'wireless'],
createdAt: new Date()
});
console.log('Inserted:', r1.insertedId); // ObjectId
// Insert many documents at once (more efficient than multiple insertOne calls)
const r2 = await products.insertMany([
{ name: 'USB-C Hub', price: 1299, category: 'Electronics', inStock: true },
{ name: 'Mouse Pad', price: 299, category: 'Accessories', inStock: true },
{ name: 'Laptop Stand', price: 899, category: 'Accessories', inStock: false }
]);
console.log('Inserted:', r2.insertedCount, 'documents');
console.log('IDs:', Object.values(r2.insertedIds));
Tip: insertMany() is much faster than calling insertOne() in a loop — it sends all documents in a single network request. For bulk imports, use insertMany() with batches of 500–1000 documents.
Finding Documents
find() returns a cursor — a lazy iterator over matching documents. Call .toArray() to get all results as an array, or iterate with for await...of for memory-efficient streaming. Use findOne() to get just the first matching document.
// Find ALL products (careful on large collections!)
const all = await products.find({}).toArray();
// Find with a filter — only in-stock products
const inStock = await products.find({ inStock: true }).toArray();
// Find one document
const laptop = await products.findOne({ name: 'Wireless Headphones' });
// Find by _id (must wrap string in ObjectId)
const { ObjectId } = require('mongodb');
const byId = await products.findOne({
_id: new ObjectId('6752ab3f1234567890abcdef')
});
// Iterate with cursor (memory-efficient for large result sets)
const cursor = products.find({ category: 'Electronics' });
for await (const doc of cursor) {
console.log(doc.name, doc.price);
}
Query Operators
MongoDB provides comparison and logical operators to build complex queries. Prefix operators with $.
// Comparison operators
await products.find({ price: { $gt: 500 } }).toArray(); // price > 500
await products.find({ price: { $gte: 500, $lte: 2000 } }).toArray(); // 500 <= price <= 2000
await products.find({ price: { $ne: 299 } }).toArray(); // price != 299
await products.find({ category: { $in: ['Electronics', 'Accessories'] } }).toArray(); // in list
await products.find({ category: { $nin: ['Clothing'] } }).toArray(); // not in list
// Logical operators
await products.find({
$and: [
{ price: { $lt: 1000 } },
{ inStock: true }
]
}).toArray();
await products.find({
$or: [
{ category: 'Electronics' },
{ price: { $lt: 400 } }
]
}).toArray();
// Field existence
await products.find({ tags: { $exists: true } }).toArray(); // has 'tags' field
// Regex search
await products.find({ name: { $regex: /^wire/i } }).toArray(); // starts with 'wire'
Projections — Controlling Returned Fields
A projection is the second argument to find(). Use 1 to include a field and 0 to exclude it. You cannot mix inclusions and exclusions (except for _id).
// Include only name and price (exclude everything else)
const names = await products.find(
{ inStock: true },
{ projection: { name: 1, price: 1 } } // _id is included by default
).toArray();
// Result: [{ _id: ObjectId(...), name: 'Headphones', price: 2499 }, ...]
// Exclude _id
const withoutId = await products.find(
{},
{ projection: { name: 1, price: 1, _id: 0 } } // _id: 0 is the ONLY allowed exclusion with inclusions
).toArray();
// Exclude specific fields (return everything except these)
const withoutDates = await products.find(
{},
{ projection: { createdAt: 0, updatedAt: 0 } } // exclude only these fields
).toArray();
Sorting, Limiting, and Skipping
// Sort by price ascending (1) or descending (-1)
const cheapest = await products
.find({ inStock: true })
.sort({ price: 1 })
.toArray();
// Limit results
const top5 = await products
.find({})
.sort({ price: -1 })
.limit(5)
.toArray();
// Pagination with skip + limit
const page = 2;
const pageSize = 10;
const results = await products
.find({})
.sort({ _id: 1 })
.skip((page - 1) * pageSize)
.limit(pageSize)
.toArray();
// Count matching documents
const count = await products.countDocuments({ category: 'Electronics' });
Warning: Avoid large skip() values for pagination — MongoDB must scan and discard all skipped documents. For large datasets, use cursor-based pagination instead: query documents where _id > lastSeenId (much more efficient).
Frequently Asked Questions
How do I find documents by _id?
Use findOne({ _id: new ObjectId('507f1f77bcf86cd799439011') }) — you must wrap the hex string in ObjectId(). Without the wrapper, MongoDB will compare the string to the ObjectId, which never matches.
What is the difference between find() and findOne()?
find() returns a cursor over all matching documents. findOne() returns just the first matching document (or null if none found). Use findOne() when you expect exactly one result, like a user by email.
How do I count documents without returning them?
Use collection.countDocuments(filter) for an accurate count with a filter, or collection.estimatedDocumentCount() for a fast approximate total count of the whole collection.