MongoDB Operation
Follow the methods available for MongoDB operations below:
Database Method (Db)
collection(name): Selects a specific collection.
Collection Methods
These are the CRUD (Create, Read, Update, Delete) methods executed on a specific collection.
Create
insertOne(doc): Inserts a single document into the collection.insertMany([docs]): Inserts multiple documents at once.
Read
find(query): Searches for multiple documents. It returns a cursor, which can be transformed into an array using.toArray().findOne(query): Searches for and returns only the first document that satisfies the filter.countDocuments(query): Counts how many documents meet the search criteria.distinct(field, query): Returns a list of unique values for a specific field.
Update
updateOne(filter, update): Updates the first document found by the filter.updateMany(filter, update): Updates all documents that match the filter.replaceOne(filter, replacement): Replaces an entire document with a new one, keeping only the_id.findOneAndUpdate(filter, update): Finds a document, applies the update, and returns the original (or the updated one, depending on options).
Delete
deleteOne(filter): Removes the first document that matches the filter.deleteMany(filter): Removes all documents that match the filter.
Aggregation and Performance Methods
aggregate(pipeline): Executes an Aggregation Framework pipeline for complex data transformations.createIndex(keys, options): Creates an index on the collection to improve search performance.drop(): Removes the entire collection from the database.
How to Reference a Collection (2 types)
Direct Access via Property (Dot Notation): Used when the collection name does not have special characters or spaces. Example:
db.usersordb.productscollection()Method with String: This is the safest and most recommended way according to the MongoDB driver documentation for Node.js. It allows the use of single or double quotes and accepts names with spaces or special characters. Example:db.collection('users')
Common operations immediately after referencing the collection
Once you have referenced the collection using one of the methods above, you generally chain the search or manipulation methods:
db.collection('users').find({})db.users.insertOne({ name: "Dev" })
Last updated
Was this helpful?
