MongoDB CRUD Operations: Create, Read, Update, Delete in mongosh and DbSchema
For developers who can open mongosh on a MongoDB database and now need to write documents and read them back; every method is shown with what it returns or leaves in the collection.
On this page
CRUD operations create, read, update and delete the documents of a MongoDB collection. For example, you can add a passenger to a passengers collection, change a seat, and remove the passenger again. DbSchema runs the same statements in its Query Editor, next to a diagram of the collections.
Every CRUD method has the same shape:
db.collection.insertOne(document)
db.collection.find(filter, projection)
db.collection.updateOne(filter, update, options)
db.collection.replaceOne(filter, replacement)
db.collection.deleteOne(filter)
dbis the database that mongosh is using.useswitches mongosh to another database.collectionis the name of the collection, such aspassengers.documentis the document to write.filterselects the documents that the method acts on.projectionlists the fields that find returns.updatenames the fields to change, with update operators such as$set.replacementis a whole document that takes the place of the stored one.optionsholds settings such asupsert.
The methods come in pairs, one for a single document and one for several:
| Operation | One document | Several documents |
|---|---|---|
| Create | insertOne() | insertMany() |
| Read | findOne() | find() |
| Update | updateOne() | updateMany() |
| Delete | deleteOne() | deleteMany() |
Create a sample collection of five passengers in a database named flights:
use flights
db.passengers.insertMany([
{ name: "Michael", age: 30, seat: 12 },
{ name: "Sarah", age: 25, seat: 18 },
{ name: "David", age: 40, seat: 22 },
{ name: "Emily", age: 28, seat: 7 },
{ name: "James", age: 35, seat: 15 }
])
MongoDB creates the passengers collection with the first insert, and gives each document a unique _id of type ObjectId. The result tables below leave out _id.
Every statement ran in mongosh 2.8.2 on MongoDB 8.2.6. Run the examples in order. Each write changes the collection.
insertOne
insertOne adds one document to a collection. For example, you can add a sixth passenger.
db.passengers.insertOne({ name: "Jennifer", age: 21, seat: 34 })
{
acknowledged: true,
insertedId: ObjectId('6af4f45ea622d9dc3344ba8e')
}
Jennifer's document had no _id, so MongoDB added an _id and returned its value as insertedId. insertMany works the same way on an array of documents.
find
find returns the documents of a collection. For example, you can list every passenger.
db.passengers.find()
| name | age | seat |
|---|---|---|
| Michael | 30 | 12 |
| Sarah | 25 | 18 |
| David | 40 | 22 |
| Emily | 28 | 7 |
| James | 35 | 15 |
| Jennifer | 21 | 34 |
All six passengers come back, in the order they were inserted. find returns a cursor, which hands over the documents in batches, and mongosh prints the first 20. Type it to print the next 20.
Filters
A filter lists the conditions that a document has to meet. For example, you can find the passengers aged 30.
db.passengers.find({ age: 30 })
| name | age | seat |
|---|---|---|
| Michael | 30 | 12 |
Only Michael is 30. For a filter that matches no document, find returns nothing and reports no error.
Comparison operators
A comparison operator, such as $gte, compares a field with a value. For example, you can find the passengers aged 30 or over.
db.passengers.find({ age: { $gte: 30 } })
| name | age | seat |
|---|---|---|
| Michael | 30 | 12 |
| David | 40 | 22 |
| James | 35 | 15 |
$gte means greater than or equal, so Michael, David and James match. The other comparison operators, such as $lt and $ne, take the same form.
findOne
findOne returns the first document that matches a filter. For example, you can find one passenger aged 30 or over.
db.passengers.findOne({ age: { $gte: 30 } })
| name | age | seat |
|---|---|---|
| Michael | 30 | 12 |
Three passengers match, and findOne returns Michael, the first of them. findOne returns the document itself rather than a cursor, and null when no document matches. updateOne and deleteOne act on the first match in the same way, and find, updateMany and deleteMany act on every match:
Which document comes first can change when MongoDB reads the collection through an index, as the findOne manual page says. To act on one particular document, filter on _id or on a field with a unique index.
Projection
A projection chooses the fields that find returns. For example, you can return only the names and seats.
db.passengers.find({ age: { $gte: 30 } }, { _id: 0, name: 1, seat: 1 })
| name | seat |
|---|---|
| Michael | 12 |
| David | 22 |
| James | 15 |
1 includes a field, and 0 excludes it. _id comes back unless the projection sets _id: 0. Apart from _id, a projection either includes fields or excludes them, never both.
sort and limit
sort sets the order of the documents from find. For example, you can list the passengers from oldest to youngest.
db.passengers.find().sort({ age: -1 })
| name | age | seat |
|---|---|---|
| David | 40 | 22 |
| James | 35 | 15 |
| Michael | 30 | 12 |
| Emily | 28 | 7 |
| Sarah | 25 | 18 |
| Jennifer | 21 | 34 |
-1 sorts from the highest age down, and 1 from the lowest up. Add .limit(3) after the sort, and find returns only David, James and Michael. MongoDB sorts first and limits after, even when limit comes before sort in the chain.
updateOne
updateOne changes the first document that matches a filter. For example, you can move Jennifer to seat 40.
db.passengers.updateOne({ name: "Jennifer" }, { $set: { seat: 40 } })
| name | age | seat |
|---|---|---|
| Jennifer | 21 | 40 |
$set writes 40 to Jennifer's seat field. mongosh replies with matchedCount: 1 and modifiedCount: 1.
updateMany
updateMany changes every document that matches a filter. For example, you can check in every passenger aged 30 or over.
db.passengers.updateMany({ age: { $gte: 30 } }, { $set: { checkedIn: true } })
| name | age | seat | checkedIn |
|---|---|---|---|
| Michael | 30 | 12 | true |
| David | 40 | 22 | true |
| James | 35 | 15 | true |
mongosh replies with matchedCount: 3 and modifiedCount: 3. The three documents had no checkedIn field, so $set added it.
replaceOne
replaceOne puts a new document in place of the first document that matches a filter. For example, you can give Emily a new seat and no age.
db.passengers.replaceOne({ name: "Emily" }, { name: "Emily", seat: 9 })
| name | seat |
|---|---|
| Emily | 9 |
The replacement has no age field, so Emily's document now has none. MongoDB keeps the document's _id.
upsert
With upsert set to true, updateOne inserts a new document when no document matches the filter. For example, you can set Chris's age and seat before Chris is in the collection.
db.passengers.updateOne(
{ name: "Chris" },
{ $set: { age: 26, seat: 14 } },
{ upsert: true }
)
{
acknowledged: true,
insertedId: ObjectId('6af4f4680302299d0e84ba47'),
matchedCount: 0,
modifiedCount: 0,
upsertedCount: 1
}
No passenger is named Chris, so matchedCount is 0 and upsertedCount is 1. MongoDB built the new document from the filter and the $set fields: Chris, age 26, seat 14. insertedId holds the new document's _id.
deleteOne
deleteOne removes the first document that matches a filter. For example, you can remove Jennifer.
db.passengers.deleteOne({ name: "Jennifer" })
The collection now holds six passengers:
| name | age | seat | checkedIn |
|---|---|---|---|
| Michael | 30 | 12 | true |
| Sarah | 25 | 18 | |
| David | 40 | 22 | true |
| Emily | 9 | ||
| James | 35 | 15 | true |
| Chris | 26 | 14 |
mongosh replies with deletedCount: 1. Jennifer is gone. A blank cell means that the document has no such field.
deleteMany
deleteMany removes every document that matches a filter. For example, you can remove every passenger aged 30 or over.
db.passengers.deleteMany({ age: { $gte: 30 } })
The collection now holds three passengers:
| name | age | seat |
|---|---|---|
| Sarah | 25 | 18 |
| Emily | 9 | |
| Chris | 26 | 14 |
mongosh replies with deletedCount: 3, for Michael, David and James. Emily stays: since the replaceOne, her document has no age field, and a condition on age can't match a missing field.
What goes wrong
An update without an operator
updateOne and updateMany need update operators, such as $set, in their second argument:
db.passengers.updateOne({ name: "Sarah" }, { seat: 20 })
Uncaught MongoInvalidArgumentError: Update document requires atomic operators
The error calls update operators atomic operators. Write { $set: { seat: 20 } } to change the seat, or use replaceOne to replace the whole document.
A duplicate _id stops insertMany
In the next insert, each document has an explicit _id, and Anna and Ben share _id: 1:
db.passengers.insertMany([
{ _id: 1, name: "Anna" },
{ _id: 1, name: "Ben" },
{ _id: 2, name: "Carl" }
])
MongoBulkWriteError: E11000 duplicate key error collection: flights.passengers index: _id_ dup key: { _id: 1 }
MongoDB inserted Anna, failed on Ben and stopped there, so Carl is missing. Pass { ordered: false } as the second argument of insertMany, and MongoDB skips each duplicate and still inserts Carl.
An empty filter matches every document
db.passengers.deleteMany({})
{ acknowledged: true, deletedCount: 4 }
The empty filter deleted all four documents: Sarah, Emily, Chris and Anna. Run a broad filter with find before you use it in a write. find shows the documents that the write would change.
CRUD operations in DbSchema
DbSchema runs MongoDB statements in its Query Editor. Connect DbSchema to MongoDB and choose Query → Query Editor. Type a statement that starts with the database name in place of db, and press Run:
flights.passengers.find({ age: { $gte: 30 } })
To draw the collections as a diagram, DbSchema reads 100 documents from the start and 100 from the end of each collection by default. It lists each field that it finds, with its BSON type. That list approximates the documents, and MongoDB doesn't enforce it.
For a collection with a $jsonSchema validator, DbSchema reads the fields from the validator instead. A virtual relation links two collections in the DbSchema model file only. DbSchema draws one where a field holds the _id of a document in another collection, and you add one by dragging a field onto another.
Right-click a collection and choose Data Explorer to browse its documents, then cascade over a virtual relation to the related documents. Export the model as HTML5 documentation to get the diagram as a vector image, with the comments of the collections and fields as mouse-over tooltips.
Download DbSchema at https://dbschema.com/download.html, connect it to your MongoDB database, and run the statements of this article in the Query Editor. The free Community Edition includes the connection, the diagram and the Query Editor. The Data Explorer, saving the model to a file, and HTML5 documentation of any size are in DbSchema Pro.
The next lesson covers embedded documents and arrays in MongoDB.