Insert Document:
To insert a document into MongoDB, you can use the insertOne()
or insertMany()
methods. The choice between the two depends on whether you want to insert a single document or multiple documents at once. Here's how to use both methods:
insertOne()
: This method inserts a single document into a collection. The syntax is as follows:
db.collectionName.insertOne(document)
- db: Refers to the current database in MongoDB. collectionName: Specifies the name of the collection where you want to insert the document. document: Represents the document (in JSON format) that you want to insert into the collection.
- Start the MongoDB shell by opening a terminal or command prompt and running the mongo command. Select the database where you want to insert the document using the use command. For example, to use a database named "mydatabase," run the following command:
use mydatabase
Define the document you want to insert in JSON format. For example, let's say we want to insert a user document into a collection named "users":
db.users.insertOne({ name: "John Doe", age: 30, email: "john@example.com" });
In this example, a document with the fields "name," "age," and "email" is inserted into the "users" collection in the "mydatabase" database.
If the "users" collection doesn't exist, MongoDB will create it automatically.
After successfully inserting the document it returns a response with" _id"
insertMany
()
: This method allows you to insert multiple documents into a collection in a single operation. The syntax is as follows:
db.collectionName.insertMany(arrayOfDocuments)
db
: Refers to the current database in MongoDB.collectionName
: Specifies the name of the collection where you want to insert the documents.arrayOfDocuments
: Represents an array containing multiple documents (in JSON format) that you want to insert.
Example of using insertMany()
:
javascript db.users.insertMany([ { name: "John Doe", age: 30, email: "john@example.com" }, { name: "Jane Smith", age: 25, email: "jane@example.com" } ]);
In this example, two documents are inserted into the "users" collection using insertMany()
. Each document is represented as an object in the documents
array.
Remember to replace "mydatabase" and "users" with your actual database and collection names.
After successfully inserting the document it returns a response with" _id"
Two records insert so it returns two _id.
Both insertOne()
and insertMany()
methods return information about the insertion, including the number of inserted documents and their corresponding IDs.
Make sure you have a running MongoDB instance and have connected to the appropriate database before attempting to insert documents.
0 Comments