Introduction to MongoDB collection.insert() Method

MongoDB is a popular NoSQL database that stores data in documents, rather than tables. The insert() method in MongoDB is used to insert a new document into a MongoDB database.

Syntax

The syntax of the MongoDB insert() method is as follows:

db.collection.insert(document, options)

Here, db.collection is the name of the collection to insert data into, document is the document to insert, and options is an optional parameter used to specify insert options.

Use Cases

The insert() method is used in the following scenarios:

  • Inserting a new document into a collection.
  • Automatically creating a collection if it doesn’t exist.
  • Inserting a new document into a collection if it already exists.
  • Failing to insert if a document with the same _id value already exists in the collection.

Example

Here is an example of using the insert() method to insert a new document:

db.users.insert({ name: "John", age: 30, email: "[email protected]" })

This will insert a new document into the users collection with the name, age, and email fields.

Here is an example of using the insert() method to insert multiple documents:

db.users.insert([
  { name: "John", age: 30, email: "[email protected]" },
  { name: "Sarah", age: 25, email: "[email protected]" },
  { name: "Bob", age: 40, email: "[email protected]" }
])

This will insert three new documents into the users collection, each with name, age, and email fields.

Conclusion

The insert() method provides a convenient way to insert new documents into a MongoDB database, both for single documents and multiple documents. Additionally, if the collection doesn’t exist, it will be automatically created. If a document with the same _id value already exists in the collection, the insert will fail.