mongodb insert document

To insert a document into a MongoDB collection, you can use the insertOne() or insertMany() method. Here are the steps to insert a document into a MongoDB collection using insertOne():

  1. Open the MongoDB shell: Open a terminal or command prompt and run the mongo command to open the MongoDB shell.

  2. Switch to the database containing the collection you want to insert the document into: Use the use command followed by the name of the database to switch to the database containing the collection. For example, to switch to a database named "mydb", run the following command:

r‮t refe‬o:theitroad.com
use mydb
  1. Insert the document: Use the insertOne() method to insert a single document into the collection. For example, to insert a document with the fields "name" and "age" into a collection named "mycollection", run the following command:
db.mycollection.insertOne({name: "John", age: 30})
  1. Confirm the document has been inserted: MongoDB will return a message indicating that the document has been inserted. You can also query the collection using the find() method to see the documents stored in the collection.

Here are the steps to insert multiple documents into a MongoDB collection using insertMany():

  1. Open the MongoDB shell: Open a terminal or command prompt and run the mongo command to open the MongoDB shell.

  2. Switch to the database containing the collection you want to insert the documents into: Use the use command followed by the name of the database to switch to the database containing the collection. For example, to switch to a database named "mydb", run the following command:

use mydb
  1. Insert the documents: Use the insertMany() method to insert multiple documents into the collection. For example, to insert two documents with the fields "name" and "age" into a collection named "mycollection", run the following command:
db.mycollection.insertMany([{name: "John", age: 30}, {name: "Jane", age: 25}])
  1. Confirm the documents have been inserted: MongoDB will return a message indicating that the documents have been inserted. You can also query the collection using the find() method to see the documents stored in the collection.