MongoDB
MongoDB CRUD Operations
Like other databases, all the basic CRUD operations are available and fully implemented in MongoDB. In this section, we will take a look at how to use some basic CRUD operations with MongoDB NodeJS driver to control your data flow.
For each type of operation, there are always 2 basic operations, one to interact with a single document, and one to interact with multiple documents
Insert Operations
Insert a Document
You can insert a document into a collection using the collection.insertOne()
method. To insert a document, define an object that contains the fields and values that you want to store. If the specified collection does not exist, the insertOne()
method will also create the collection for you.
You can specify additional query options using the options
parameter. For more information on the method parameters, see the insertOne() API documentation.
If the operation successfully inserts a document, it appends an insertedId
field to the object passed in the method call and sets the value of the field to the _id
of the inserted document.
Example:
const database = client.db("insertDB")
const haiku = database.collection("haiku")
// document to be inserted
const doc = {
title: "Record of a Shriveled Datum",
content: "No bytes, no problem. Just insert a document, in MongoDB",
}
const result = await haiku.insertOne(doc)
collection.insertOne()
will return an object with 2 fields:
acknowledged
: boolean. Indicates whether this writing result was acknowledged.insertedId
: type of_id
. The identifier that was inserted.
Insert Multiple Documents
You can insert multiple documents using the collection.insertMany()
method. The insertMany()
takes an array of documents to insert into the specified collection.
You can specify additional options in the options
object passed as the second parameter of the insertMany()
method. For more information on the method parameters, see the insertMany() API documentation.
Example:
const database = client.db("insertDB");
const foods = database.collection("foods");
// create an array of documents to insert
const docs = [
{ name: "cake", healthy: false },
{ name: "lettuce", healthy: true },
{ name: "donut", healthy: false }
];
// this option prevents additional documents from being inserted if one fails
const options = { ordered: true };
const result = await foods.insertMany(docs, options);
collection.insertMany()
result is an object with 3 fields:
acknowledged
: boolean. Indicates whether this write result was acknowledged.insertedCount
: number. The number of inserted documents for this operations.insertedIds
: map. Map of the index of the inserted document to the id of the inserted document.
Find Operations
Find a Document
You can query for a single document in a collection with the collection.findOne()
method. The findOne()
method uses a query document that you provide to match only the subset of the documents in the collection that match the query. If you don't provide a query document or if you provide an empty document, MongoDB matches all documents in the collection. The findOne()
operation only returns the first matched document. For more information on querying MongoDB, see our documentation on query documents.
You can specify the additional options in the options object passed as the second parameter of the findOne
method. For detailed reference documentation, see collection.findOne(). Example: The following snippet finds a single document from the movies
collection. It uses the following parameters:
- A query document that configures the query to return only movies with the title of exactly the text
'The Room'
. - A sort that organizes matched documents in descending order by rating, so if our query matches multiple documents the returned document will be the document with the highest rating.
- A projection that explicitly excludes the
_id
field from returned documents and explicitly includes only thetitle
andimdb
object (and its embedded fields).
const database = client.db("sample_mflix");
const movies = database.collection("movies");
// Query for a movie that has the title 'The Room'
const query = { title: "The Room" };
const options = {
// sort matched documents in descending order by rating
sort: { "imdb.rating": -1 },
// Include only the `title` and `imdb` fields in the returned document
projection: { _id: 0, title: 1, imdb: 1 },
};
const movie = await movies.findOne(query, options);
The movie
returned from the database will be something like this:
{ title: 'The Room', imdb: { rating: 3.5, votes: 25673, id: 368226 } }
Find Multiple Documents
You can query for multiple documents in a collection with collection.find()
. The find()
method uses a query document that you provide to match the subset of the documents in the collection that match the query. If you don't provide a query document (or if you provide an empty document), MongoDB returns all documents in the collection. For more information on querying MongoDB, see our documentation on query documents.
You can specify the additional options in the options object passed as the second parameter of the find
method. For detailed reference documentation, see collection.find().
Unlike findOne()
returns the found document as the result, the find()
method returns a FindCursor that manages the results of your query. You can then iterate through the matching documents using one of the following cursor methods:
next()
toArray()
forEach()
If no documents match the query, find()
returns an empty cursor.
Example:
The following snippet finds documents from the movies
collection. It uses the following parameters:
- A query document that configures the query to return only movies with a runtime of less than 15 minutes.
- A sort that organizes returned documents in ascending order by title (alphabetical order in which "A" comes before "Z" and "1" before "9").
- A projection that explicitly excludes the
_id
field from returned documents and explicitly includes only thetitle
andimdb
object (and its embedded fields).
const database = client.db("sample_mflix");
const movies = database.collection("movies");
// query for movies that have a runtime less than 15 minutes
const query = { runtime: { $lt: 15 } };
const options = {
// sort returned documents in ascending order by title (A->Z)
sort: { title: 1 },
// Include only the `title` and `imdb` fields in each returned document
projection: { _id: 0, title: 1, imdb: 1 },
};
const cursor = movies.find(query, options);
// print a message if no documents were found
if ((await cursor.count()) === 0) {
console.log("No documents found!");
}
await cursor.forEach(console.dir);
The above code will result in something like the following output:
{ title: '10 Minutes', imdb: { rating: 7.9, votes: 743, id: 339976 } }
{ title: '3x3', imdb: { rating: 6.9, votes: 206, id: 1654725 } }
{ title: '7:35 in the Morning', imdb: { rating: 7.3, votes: 1555, id: 406501 } }
{ title: '8', imdb: { rating: 7.8, votes: 883, id: 1592502 } }
...
You should know
The sort
and projection
options can also be specified as methods chained to the find
method. The following two expressions are equivalent:
collection.find(
{ runtime: { $lt: 15 } },
{
sort: { title: 1 },
projection: { _id: 0, title: 1, imdb: 1 }
}
);
collection.find({ runtime: { $lt: 15 } })
.sort({ title: 1})
.project({ _id: 0, title: 1, imdb: 1 });
You should know
If you just want to count the amount of documents that match the query document, you can use countDocuments()
operation.
Update Operations
Update a Document
You can update a single document using the collection.updateOne()
method. The updateOne()
method accepts a filter document and an update document. If the query matches documents in the collection, the method applies the updates from the update document to fields and values of them. The update document contains update operators that instruct the method on the changes to make to the matches.
You can specify additional query options using the options
object passed as the second parameter of the updateOne()
method. Set the upsert
option to true
to create a new document if no documents match the filter. For additional information, see the updateOne() API documentation.
Example
The following example uses the $set
update operator which specifies update values for document fields. For more information on update operators, see the MongoDB update operator reference documentation.
const database = client.db("sample_mflix");
const movies = database.collection("movies");
// create a filter for a movie to update
const filter = { title: "Random Harvest" };
// this option instructs the method to create a document if no documents match the filter
const options = { upsert: true };
// create a document that sets the plot of the movie
const updateDoc = {
$set: {
plot: `A harvest of random numbers, such as: ${Math.random()}`
},
};
const result = await movies.updateOne(filter, updateDoc, options);
The result
is an object with the following fields:
acknowledged
: boolean. Indicates whether this write result was acknowledged.matchedCount
: number. The number of documents that matched the filter.modifiedCount
: number. The number of documents that were modified.upsertedCount
: number. The number of documents that were upserted.upsertedId
: ObjectId. The identifier of the inserted document if an upsert took place
You should know
Alternally, you can use the compound operation called findOneAndUpdate()
which will basically do the same as updateOne()
but instead return the updated document as the result, you can also configure sort
and projection
options that work just like the read operations equivalents. There's also an option called returnDocument
to determine if the returned document is pre-update or post-update version.
Update Multiple Documents
To update multiple documents you can use the collection.updateMany()
method. The updateMany()
schema is like updateOne() accepts a filter document and an update document. If the query matches documents in the collection, the method applies the updates from the update document to all matching documents. The update document requires an update operator to modify a field in a document.
You can specify additional options in the options
object passed in the third parameter of the updateMany()
method. For more detailed information, see the updateMany() API documentation.
Example:
const database = client.db("sample_mflix");
const movies = database.collection("movies");
// create a filter to update all movies with a 'G' rating
const filter = { rated: "G" };
// increment every document matching the filter with 2 more comments
const updateDoc = {
$set: {
random_review: `After viewing I am ${
100 * Math.random()
}% more satisfied with life.`,
},
};
const result = await movies.updateMany(filter, updateDoc);
The result
is an object with the following fields:
acknowledged
: boolean. Indicates whether this write result was acknowledged.matchedCount
: number. The number of documents that matched the filter.modifiedCount
: number. The number of documents that were modified.upsertedCount
: number. The number of documents that were upserted.upsertedId
: ObjectId. The identifier of the inserted document if an upsert took place
Delete Operations
Delete a Document
You can delete a single document in a collection with collection.deleteOne()
. The deleteOne()
method uses a query document that you provide to match the subset of the documents in the collection that match the query. If you do not provide a query document (or if you provide an empty document), MongoDB matches all documents in the collection and deletes the first match.
You can specify additional query options using the options
object passed as the second parameter of the deleteOne
method. For more information on this method, see the deleteOne() API documentation.
Example:
The following snippet deletes a single document from the movies
collection. It uses a query document that configures the query to match movies with a title
value of "Annie Hall".
const database = client.db("sample_mflix");
const movies = database.collection("movies");
// Query for a movie that has title "Annie Hall"
const query = { title: "Annie Hall" };
const result = await movies.deleteOne(query);
The result
will contains 2 fields:
acknowledged
: boolean. Indicates whether this write result was acknowledged.deletedCount
: number. The number of documents that were deleted.
You should know
Alternally, you can use the compound operation called findOneAndDelete()
which will basically do the same as deleteOne()
but instead return the deleted document as the result
Delete Multiple Documents
You can delete multiple documents in a collection at once using the collection.deleteMany()
method. Pass a query document to the deleteMany()
method to specify a subset of documents in the collection to delete. If you do not provide a query document (or if you provide an empty document), MongoDB matches all documents in the collection and deletes them. While you can use deleteMany()
to delete all documents in a collection, consider using drop() instead for better performance and clearer code.
You can specify additional options
in the options object passed in the second parameter of the deleteMany()
method. For more detailed information, see the deleteMany() API documentation.
Example:
The following snippet deletes multiple documents from the movies
collection. It uses a query document that configures the query to match and delete movies with the title "Santa Claus".
const database = client.db("sample_mflix");
const movies = database.collection("movies");
// Query for all movies with a title containing the string "Santa"
const query = { title: { $regex: "Santa" } };
const result = await movies.deleteMany(query);
The result
will contains 2 fields:
acknowledged
: boolean. Indicates whether this write result was acknowledged.deletedCount
: number. The number of documents that were deleted.