On this page
CRUD Operations
Create
Inserting Documents
-
insertOne(document)
- Inserts a single document into a collection.
- Example:
db.collectionName.insertOne({ name: "John Doe", age: 30, city: "New York" });
-
insertMany(documents)
- Inserts multiple documents into a collection.
- Example:
db.collectionName.insertMany([ { name: "Alice", age: 25, city: "Los Angeles" }, { name: "Bob", age: 28, city: "Chicago" } ]);
Read
Querying Documents
-
find(query)
- Retrieves multiple documents that match the query.
- Example:
db.collectionName.find({ age: { $gt: 25 } });
-
findOne(query)
- Retrieves a single document that matches the query.
- Example:
db.collectionName.findOne({ name: "John Doe" });
Query Operators
-
$eq
(Equal)- Matches values that are equal to a specified value.
- Example:
db.collectionName.find({ age: { $eq: 30 } });
-
$gt
(Greater Than)- Matches values that are greater than a specified value.
- Example:
db.collectionName.find({ age: { $gt: 25 } });
-
$lt
(Less Than)- Matches values that are less than a specified value.
- Example:
db.collectionName.find({ age: { $lt: 30 } });
Projection (Selecting Specific Fields)
- Projection allows you to specify which fields to include or exclude in the results.
- Example:
db.collectionName.find( { age: { $gt: 25 } }, { projection: { name: 1, city: 1 } } );
- The above command retrieves only the
name
andcity
fields.
Update
Updating Documents
-
updateOne(filter, update)
- Updates a single document that matches the filter.
- Example:
db.collectionName.updateOne( { name: "John Doe" }, { $set: { age: 31 } } );
-
updateMany(filter, update)
- Updates multiple documents that match the filter.
- Example:
db.collectionName.updateMany( { city: "New York" }, { $set: { status: "active" } } );
Update Operators
-
$set
- Sets the value of a field in a document.
- Example:
Copy code db.collectionName.updateOne( { name: "John Doe" }, { $set: { age: 31 } } );
-
$unset
- Removes a field from a document.
- Example:
db.collectionName.updateOne( { name: "John Doe" }, { $unset: { city: "" } } );
-
$inc
- Increments the value of a field by a specified amount.
- Example:
db.collectionName.updateOne( { name: "John Doe" }, { $inc: { age: 1 } } );
Delete
Deleting Documents
-
deleteOne(filter)
- Deletes a single document that matches the filter.
- Example:
db.collectionName.deleteOne({ name: "John Doe" });
-
deleteMany(filter)
- Deletes multiple documents that match the filter.
- Example:
db.collectionName.deleteMany({ age: { $lt: 20 } });