
{{ $('Map tags to IDs').item.json.title }}
How to Insert Documents in MongoDB
Inserting documents into MongoDB collections is a fundamental operation when working with NoSQL databases. MongoDB stores data in flexible document formats, similar to JSON objects. This tutorial will guide you through the steps of inserting documents into MongoDB collections using the MongoDB shell.
1. Logging into MongoDB
First, open your terminal and log into the MongoDB shell with:
mongo
This connects you to the locally running MongoDB server.
2. Selecting a Database
After logging in, select the database where you want to insert documents:
use my_database
Replace my_database
with the name of your target database. If the database does not exist, MongoDB will create it on the first insertion.
3. Inserting a Single Document
To insert a single document into a collection, use the insertOne()
method. For example, to insert a document into the users
collection:
db.users.insertOne({ name: 'Alice', age: 25, email: '[email protected]' });
This command adds a new document with the specified fields to the users
collection.
4. Inserting Multiple Documents
To insert multiple documents at once, you can use the insertMany()
method:
db.users.insertMany([
{ name: 'Bob', age: 30, email: '[email protected]' },
{ name: 'Charlie', age: 28, email: '[email protected]' }
]);
This command inserts multiple documents into the users
collection in a single operation.
5. Checking Inserted Documents
To confirm that your documents have been inserted, use:
db.users.find().pretty()
This command retrieves and formats all documents in the users
collection for easy reading.
6. Conclusion
By following this tutorial, you have learned how to effectively insert documents into MongoDB collections. Inserting data correctly is essential for successful database management and application functionality. Continue to explore MongoDB’s features and document structures to enhance your data manipulation skills!