Introduction to MongoDB collection.insertOne() Method
MongoDB is a popular NoSQL database that stores data in documents instead of tables. The insertOne()
method in MongoDB is used to insert a single new document into a database.
Syntax
The syntax for the insertOne()
method in MongoDB is as follows:
db.collection.insertOne(document, options)
Here, db.collection
is the name of the collection to insert data into, document
is a document object representing the document to be inserted, and options
is an optional parameter for specifying insertion options.
Use Cases
The insertOne()
method is useful in the following situations:
- Inserting a single new document into a collection.
- If the collection doesn’t exist, it will be created automatically.
- If the collection already exists, a new document will be inserted into it.
- If a document with the same
_id
value already exists in the collection, the insertion will fail.
Examples
Here is an example of using the insertOne()
method to insert a single new document:
db.users.insertOne({ name: "John", age: 30, email: "[email protected]" })
This will insert a new document with name
, age
, and email
fields into the users
collection.
Here is an example of using the insertOne()
method with options to insert a new document:
db.users.insertOne(
{ name: "John", age: 30, email: "[email protected]" },
{ writeConcern: { w: "majority" } }
)
This will insert a new document into the users
collection and use the { writeConcern: { w: "majority" } }
option to specify that the write operation should wait for a majority of nodes to respond.
Conclusion
The insertOne()
method is a convenient way to insert a single new document into a MongoDB database, including automatically creating a collection if it doesn’t already exist. If a document with the same _id
value already exists in the collection, the insertion will fail.