Inserting and finding documents
CRUD (Create, Read, Update, Delete) is most of what an app does with a database. This lesson covers the C and the R: putting documents in and getting them back out.
Creating documents
insertOne adds a single document. If the collection doesn't exist yet, MongoDB creates it automatically:
The reply includes the generated insertedId. insertMany adds several at once:
Notice Sapiens has a rating field and the others don't. That's fine: documents in a collection don't have to share a shape.
Your own _id
You can provide _id yourself, for example a natural unique key. It must be unique in the collection:
That E11000 duplicate key error is the error you'll see whenever a unique rule is broken.
What an ObjectId contains
An ObjectId is 12 bytes: a 4-byte timestamp, then random and counter bytes. So it's roughly sortable by creation time, and you can read when a document was created:
Finding documents
find(filter) returns every document matching the filter. An empty filter {} matches everything:
findOne(filter) returns the first match, or null:
Several conditions = AND
Nested fields: dot notation
Reach inside embedded objects with a dotted path, in quotes:
Arrays match by element
When a field is an array, a filter like { tags: 'vip' } matches documents where any element equals 'vip':
Choosing fields: projection
The second argument to find is a projection: which fields to return. 1 includes, 0 excludes. _id is included unless you exclude it:
Returning only the fields you need makes responses smaller and faster. (You'll learn $lt and friends in the query operators lesson.)
Counting and distinct values
Working with results in JavaScript
mongosh is a JavaScript environment, so you can store results in variables and use normal JavaScript:
Practice
- Insert three movies (title, year, genres array, and a rating for just one of them) into a
moviescollection. - Find all movies with the genre
'drama'. - Find the customers from the UK, returning only their names and emails.
1.What happens if you insert into a collection that doesn't exist?
2.What does db.customers.find({ tags: 'vip' }) match?
3.What does the projection { name: 1, _id: 0 } return?