Inserting Documents in MongoDB
Inserting Documents in MongoDB
Introduction
In MongoDB, documents are inserted into collections, which are analogous to tables in relational databases. This tutorial will cover the different commands you can use to insert documents into MongoDB collections.
Prerequisites
MongoDB installed and running on your machine.
Access to
mongosh
.
Step 1: Start mongosh
mongosh
Open Terminal/Command Prompt:
Launch your terminal (macOS/Linux) or command prompt (Windows).
Start
mongosh
:Type the following command and press Enter:
Step 2: Switch to the Database
Switch to the desired database where you want to insert documents.
Use a Database:
Step 3: Insertion Commands
1. Inserting a Single Document
To insert a single document into a collection, use the insertOne()
method.
2. Inserting Multiple Documents
To insert multiple documents at once, use the insertMany()
method.
3. Inserting a Document with a Specific _id
_id
You can specify a unique _id
for the document during insertion. If you do not specify it, MongoDB will automatically generate one.
4. Inserting Documents with Arrays
You can also insert documents that contain arrays.
5. Inserting Nested Documents
You can insert documents that contain other documents (nested documents).
Conclusion
You have learned how to use various insertion commands in MongoDB using mongosh
, including inserting single documents, multiple documents, documents with specific _id
s, arrays, and nested documents. Feel free to experiment with these commands in your MongoDB environment!
If you have any questions or need further guidance, feel free to ask!
Last updated