Create in MongoDB
Creating data in MongoDB involves inserting documents into collections. A document is essentially a record that contains data in field-value pairs. MongoDB provides various methods to insert data, and here's a detailed look at some of the most commonly used ones:
Inserting a Single Document
To insert a single document into a collection, you can use the insertOne()
method. This method takes one argument: the document you want to insert.
Syntax:
db.collectionName.insertOne(document)
Example:
db.users.insertOne({
username: "john_doe",
email: "john.doe@example.com",
age: 30
})
When you insert a document without specifying an _id
field, MongoDB automatically generates a unique _id
for the document.
Return Value:
The method returns an object containing the _id
of the inserted document, which can be useful for further operations.
Inserting Multiple Documents
To insert multiple documents at once, you can use the insertMany()
method. This method takes an array of documents as its argument.
Syntax:
db.collectionName.insertMany([document1, document2, ...])
Example:
db.users.insertMany([
{ username: "john_doe", email: "john.doe@example.com", age: 30 },
{ username: "jane_doe", email: "jane.doe@example.com", age: 25 },
{ username: "sam_smith", email: "sam.smith@example.com", age: 22 }
])
Return Value:
The method returns an object containing the _id
s of all the inserted documents.
Bulk Write Operations
For more complex scenarios where you want to perform multiple create, update, or delete operations in a single command, you can use the bulkWrite()
method.
Syntax:
db.collectionName.bulkWrite([
{ insertOne: { "document": { field1: value1, field2: value2 } } },
{ updateOne: { filter: { field1: value1 }, update: { $set: { field2: value2 } } } },
{ deleteOne: { filter: { field1: value1 } } },
...
])
Example:
db.users.bulkWrite([
{ insertOne: { "document": { username: "john_doe", email: "john.doe@example.com", age: 30 } } },
{ insertOne: { "document": { username: "jane_doe", email: "jane.doe@example.com", age: 25 } } },
{ updateOne: { filter: { username: "john_doe" }, update: { $set: { age: 31 } } } }
])
Return Value:
The method returns an object containing detailed information about the operations performed, such as the number of inserted, updated, and deleted documents.
Embedded documents
In MongoDB, embedded documents are documents that are nested inside other documents. This is a powerful feature that allows you to store related pieces of information together in a single document, which can make querying more efficient. Embedded documents capture relationships between data by storing related information in a single document structure.
Structure
In MongoDB, you can embed a document within another document as a subdocument. The embedded document will be a field in the parent document and will be enclosed in curly braces {}
.
Example:
{
"_id": ObjectId("5f50c31b8501f31a91c0f3b4"),
"name": "John",
"address": {
"street": "123 Main St",
"city": "Springfield",
"state": "IL",
"zip": "62704"
}
}
In this example, the address
field is an embedded document containing related information about the user's address.
Advantages
- Data Locality: All related data is stored together, which can make queries more efficient.
- Atomic Operations: Because embedded documents are part of the parent document, operations on the parent document are atomic at the document level.
- Schema Flexibility: Each embedded document can have its own structure.
Limitations
- Document Size: The maximum BSON document size in MongoDB is 16MB, so the sum of the sizes of the embedded documents must not exceed this limit.
- Complex Queries: Queries can become more complex when you have multiple levels of embedded documents.
- Data Duplication: If you're embedding data that is not truly a sub-part of the parent document, you may end up with data duplication.
- Nested level limitation: There are maximum 100 levels are allowed to nested document in document.
Querying Embedded Documents
You can query embedded documents using dot notation.
Example:
db.users.find({ "address.city": "Springfield" })
Updating Embedded Documents
You can also update embedded documents using dot notation along with update operators like $set
.
Example:
db.users.updateOne({ "address.city": "Springfield" }, { $set: { "address.zip": "62705" } })
When to Use Embedded Documents
- One-to-One Relationships: When there is a one-to-one mapping between entities.
- One-to-Few: When one entity is related to a few other entities, and there's a need to frequently access them together.
- Data Cohesion: When there's a strong need to use the embedded data only in the context of the parent document.