MongoDB - Basic CRUD Operations
In MongoDB documents can be inserted to collections. Collections reside inside databases.
Setting Up
We need to first specify the database that we will be using. Let's switch to the database test:
After that, let's create a document called users:
Built-In IDs
Each MongoDB document has a built-in ID. So whenever you insert a new document inside a collection, the document will always get an unique ID for itself.
For example, two documents stored in the cars collection could look like this:
[
{
_id: ObjectId("62aae293adec45e9cb477b3b"), // (1)!
manufacturer: 'Ford',
model: 'Mondeo'
},
{
_id: ObjectId("62aae293adec45e9cb477b3b"), // (2)!
manufacturer: 'Tesla',
model: 'Model 3'
},
],
- Automatically generated by MongoDB when the document was inserted.
- Automatically generated by MongoDB when the document was inserted.
Inserting Documents
To add one or many documents to MongoDB collection, the commands db.collection.insertOne() and db.collection.insertMany can be used.
For example:
Note that the example above only contained text and number for the field data types. You can see also from the above that as MongoDB does not enforce any kind of schema by default, any kind of documents can also be stored inside collections.
For example: