In MongoDB, we can manually insert a document into a collection in the selected database using db.collection_name.insert() method. We can also insert a document using the upsert method into a collection in the selected database using db.collection_name.update() or db.collection_name.save() method in MongoDB.
- Type the command use DATABASE_NAME in the command prompt to create a new database or to select the already created database with the respective name.
For Example: use Hellodb
- Type the command createCollection(name, options) in the command prompt to create a new collection manually.
For Example: db.createCollection(“HELLO”)
- Type the command Collection_Name.insert(Document_name) to insert a document into the already created collection.
For Example: db.HELLO.insert ({“name”: “welcome”})
- For automatic creation of the collection directly insert a document into a collection with the desired name using the Collection_Name.insert(Document_name) command.
For Example: db.HELLO.insert ({“name”: “welcome”})
- Type the command collection_name.find() in the command prompt to see the inserted document in a collection.
For Example: db.HELLO.find()
- To insert multiple documents in a collection, pass an array of documents to the Collection_Name.insert(Array_name) method.
For Example: db.HELLO.insert (“docArray”)
- Type the command collection_name.find() in the command prompt to see the inserted array of documents in a collection.
For Example: db.HELLO.find()
- Type the command var bulk = db.Collection_Name.initializeUnorderedBulkOp() to initialize a bulk operation builder for the collection in order to perform multiple write operations in bulk.
For Example: db.HELLO.initializeUnorderedBulkOp()
- Type the command insert() to add the insert operations to the bulk object.
- Type the command execute() to execute the insertion operation along with any other bulk operations.