Collections and CRUD Operations
🎯 Introduction
In the previous article, we started the mongo-demo container with Docker and connected to MongoDB with mongosh. In this lesson, you will learn about databases and collections, and perform the four basic operations: creating, reading, updating, and deleting data, commonly called CRUD. These operations are central to everyday MongoDB use and underpin the rest of this course.
Run all commands in this article in mongosh. If you are not connected yet, run:
docker exec -it mongo-demo mongosh -u root -p 123456 --authenticationDatabase admin
🧱 Databases and Collections
A MongoDB server can contain multiple independent databases. Using Excel as an analogy, each database is a workbook, each collection is a worksheet, and each individual data entry is a document.
Switch to the example database, blog_demo:
use blog_demo
use succeeds even if blog_demo does not exist. MongoDB does not require databases or collections to be created in advance: they are created when you insert the first document. Think of use blog_demo as selecting where subsequent operations will run; the database is created when you actually write data.Collections work the same way. Inserting the first document into user creates the collection automatically. To create one explicitly, for example to configure collection-level options, use:
db.createCollection('user')
use blog_demo applies only to the current connection. If you close mongosh and reconnect, run it again to select your database.The mongosh variable db represents the current database. We will use it throughout these CRUD examples: db.user refers to the user collection in that database.
✨ Inserting Data with insertOne
Let's add some data to the empty collection. To insert one document, pass an object to insertOne:
db.user.insertOne({ username: 'Zhang San', age: 25, city: 'Beijing' })
A successful operation returns a result like this:
{
acknowledged: true,
insertedId: ObjectId('66f1a2b3c4d5e6f7a8b9c0d1')
}
acknowledged: truemeans the write was acknowledged.insertedIdis the document's_id, automatically generated by MongoDB as a globally unique identifier. You do not need to create it yourself.
ObjectId('...') is generated on your machine, so it is normal for it to differ from the example. You can use _id to locate a specific document later.To insert several documents at once, pass an array to insertMany:
db.user.insertMany([
{ username: 'Li Si', age: 30, city: 'Shanghai' },
{ username: 'Wang Wu', age: 22, city: 'Guangzhou' },
{ username: 'Zhao Liu', age: 28, city: 'Shenzhen' },
])
The result includes an insertedIds object containing the _id of each new document.
💡 Reading Data with find
Use find to query documents, a frequent operation in everyday development. Without a filter, it retrieves every document in the collection:
db.user.find()
You should see the four documents you inserted, each with an automatically generated _id. By default, find returns all fields, so you do not need to specify individual columns.
To retrieve just one document, use findOne with a filter:
db.user.findOne({ username: 'Zhang San' })
The first argument is a query filter, expressed as an object. { username: 'Zhang San' } means the username field equals Zhang San. find accepts the same filter, but returns all matches, while findOne returns only the first:
db.user.find({ city: 'Shanghai' })
For now, we will use simple equality filters. The next article covers richer conditions, including comparisons and combinations of filters.
⚡ Updating Data with updateOne
Use updateOne to change existing data. For example, suppose Zhang San moves to Hangzhou:
db.user.updateOne({ username: 'Zhang San' }, { $set: { city: 'Hangzhou' } })
It takes two arguments:
- The first is a filter, written like a
findfilter, identifying the documents to update. - The second describes the update.
$setassigns values to the specified fields and leaves all other fields unchanged.
The result includes a few useful counts:
{
acknowledged: true,
matchedCount: 1,
modifiedCount: 1,
// ...other fields omitted
}
matchedCount: The number of documents matching the filter.modifiedCount: The number actually changed. If the new value equals the old value, the document matches but is not modified, so this count is 0.
updateOne changes only the first matching document. To update every match, use updateMany:
db.user.updateMany({ city: 'Guangzhou' }, { $set: { city: 'Zhuhai' } })
$set in the second argument when updating these fields. Writing db.user.updateOne({ username: 'Zhang San' }, { city: 'Hangzhou' }) does not express a field update. Keep the distinction between updating fields and replacing an entire document clear: a replacement containing only city would remove fields such as username and age.🪤 Deleting Data with deleteOne
Use deleteOne or deleteMany to remove documents. For example, delete Zhao Liu's document:
db.user.deleteOne({ username: 'Zhao Liu' })
The result's deletedCount tells you how many documents were deleted. deleteOne deletes the first match, whereas deleteMany deletes every match:
db.user.deleteMany({ city: 'Zhuhai' })
Deletion cannot be undone. First run find with the same filter to confirm which documents will be deleted:
db.user.find({ city: 'Zhuhai' })
Once you have checked the result, run the corresponding deleteMany.
db.user.deleteMany({}) deletes all documents. Make it a habit to run find with the same filter before deleting, and confirm that the matches are the documents you intend to process.❓ Questions and Answers
Q1: Do I need to define fields before inserting data?
No. MongoDB collections have no fixed field structure: the fields you insert are the fields stored. In real projects, consistent fields within a collection still make your code easier to maintain.
Q2: Can I specify _id myself?
Yes. Include an _id field when inserting, but make sure it is unique; duplicates cause an error. Usually, letting MongoDB generate it is sufficient.
Q3: What if find returns more data than fits on the screen?
mongosh displays results in batches. Enter it, short for iterate, to display the next batch. In applications, you will usually use filters and limits, which we will cover later.
Q4: What happens if several documents match an updateOne filter?
Only the first match is updated. Use updateMany to change them all. If you are unsure how many documents match, run find with the same filter first.
Q5: How can I confirm an update succeeded?
Check modifiedCount, then retrieve the document with find to inspect it. Checking after an update helps catch incorrect filters early.
🧪 Exercises
Complete these two operations in the user collection:
- Insert your own document with any username and your actual age and city.
// Write your code here
- Change that document's city to Chengdu, then retrieve it to confirm the update.
// Write your code here
🎉 You can now work with collections and perform CRUD operations! Next, we will use richer query filters, including comparisons and combined conditions, to retrieve precisely the documents you need.
