DEV Community

Parth
Parth

Posted on • Originally published at devsarticles.com

How To Use MongoDB InsertOne() For Single Document Insertion?

MongoDB's insertOne() method serves the specific purpose of inserting a singular document into a collection, akin to adding a single record to a table in relational database management systems (RDBMS). Unlike the more flexible insert() method, which allows for the insertion of one or more documents, insertOne() focuses solely on adding one document at a time, providing granular control over individual insertions.

How MongoDB insertOne() Works?

To utilize insertOne(), you simply invoke the method with the syntax db..insertOne(), where db refers to the current database and denotes the target collection.

db.<collection>.insertOne(document, [writeConcern])
Enter fullscreen mode Exit fullscreen mode
  1. Document: Represents the specific data to be inserted into the collection, formatted as a document.
  2. WriteConcern: An optional parameter allowing you to specify the desired write concern, overriding the default setting for the insertion operation.

Example of MongoDB insertOne()

// Adding a new product to the database
db.products.insertOne({ 
    productName: "Smartphone",
    brand: "TechPhone",
    price: 492.92
})

Enter fullscreen mode Exit fullscreen mode

Upon successful execution, MongoDB provides a response indicating whether the insertion was acknowledged and the unique identifier assigned to the newly added document.

{
  acknowledged: true,
  insertedId: ObjectId("617a2e9ea861820797edd9c1")
}
Enter fullscreen mode Exit fullscreen mode

Extra Features of MongoDB insertOne()

  1. Schemaless MongoDB: Unlike traditional databases, MongoDB does not enforce a rigid schema, allowing for flexibility in data structure. This means you can insert data with varying structures into the same collection without adhering to a predefined format.
  2. Manual _id Insertion: MongoDB allows you to manually specify a unique identifier (_id) for a document, giving you control over the identification process. This can be useful for ensuring data integrity and avoiding duplicate keys.

How To Use MongoDB InsertOne() For Single Document Insertion? - Devsarticles

Explore the seamless process of MongoDB InsertOne. Ensuring efficient data insertion And Mastering this crucial database operation.

favicon devsarticles.com

Top comments (0)