How To Use MongoDB InsertOne() For Single Document Insertion?
Parth
Posted on February 25, 2024
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])
- Document: Represents the specific data to be inserted into the collection, formatted as a document.
- 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
})
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")
}
Extra Features of MongoDB insertOne()
- 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.
- 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.
Posted on February 25, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.