⬅ Previous Topic
Using MongoDB ShellNext Topic ⮕
Read Operations in MongoDB⬅ Previous Topic
Using MongoDB ShellNext Topic ⮕
Read Operations in MongoDBIn MongoDB, inserting data means adding new documents to a collection. You don't need to predefine the schema or structure of your data, making it flexible and fast to use. MongoDB provides two main methods for insert operations:
insertOne()
– inserts a single documentinsertMany()
– inserts multiple documents at onceThis method is used to insert a single document into a collection. If the collection doesn’t exist yet, MongoDB will automatically create it for you.
insertOne()
to insert a document
mongo
use mydb
db.users.insertOne({
name: "Alice",
age: 25,
email: "alice@example.com"
});
Output:
{ acknowledged: true, insertedId: ObjectId("...") }
Explanation: The document is inserted into the users
collection. MongoDB auto-generates a unique _id
field for each document if not provided.
Q: What happens if the users
collection doesn't exist yet?
A: MongoDB will automatically create the collection when you insert the first document. You don’t need to explicitly create it beforehand.
This method is used to insert multiple documents into a collection in one operation. It's more efficient than calling insertOne()
multiple times.
db.products.insertMany([
{
name: "Laptop",
brand: "Dell",
price: 70000
},
{
name: "Phone",
brand: "Samsung",
price: 30000
},
{
name: "Tablet",
brand: "Apple",
price: 50000
}
]);
Output:
{ acknowledged: true, insertedIds: { "0": ObjectId("..."), "1": ObjectId("..."), "2": ObjectId("...") } }
Explanation: Each document in the array is inserted into the products
collection. The insertedIds
map shows the index and ID of each inserted document.
Q: Can documents inserted with insertMany()
have different fields?
A: Yes! MongoDB allows documents with different fields in the same collection. It doesn’t enforce a fixed schema.
You can also specify your own _id
field if you want full control over the document identifier.
db.users.insertOne({
_id: "user123",
name: "Bob",
age: 28
});
Output:
{ acknowledged: true, insertedId: "user123" }
Explanation: The document uses a custom string _id
instead of the default ObjectId. This can be useful when integrating with external systems that use predefined IDs.
Q: What happens if you insert another document with the same _id
?
A: MongoDB will throw a duplicate key error. The _id
must be unique within the collection.
insertOne()
adds a single documentinsertMany()
adds multiple documents efficiently_id
values, but they must be uniqueIn the next topic, we will learn how to read documents from the collection using powerful querying features like find()
and filters.
⬅ Previous Topic
Using MongoDB ShellNext Topic ⮕
Read Operations in MongoDBYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.