MongoDB – Sample Document Creation
Let’s look at how to create and interact with documents in MongoDB.
Step 1: Install MongoDB (if not installed)
To get started, you need to install MongoDB on your machine. After installation, MongoDB provides a command-line shell (mongo shell) to interact with the database.
Step 2: Start MongoDB Server
Make sure MongoDB is running by starting the MongoDB server:
mongod
Step 3: Connect to MongoDB
Open the MongoDB shell by typing:
mongo
Step 4: Create a Database
In MongoDB, you first create a database. If the database doesn’t exist, it will be created when you insert data into it.
use insuranceDB
This will switch to the insuranceDB database. If it doesn’t exist, MongoDB will create it when you add documents.
Step 5: Create a Collection and Insert Documents
You can create a collection (similar to a table in relational databases) and insert documents into it. Here’s an example of how to insert an insurance policy document:
db.policies.insertOne({
policyNumber: "INS123456",
policyHolder: {
firstName: "John",
lastName: "Doe",
address: {
street: "123 Main St",
city: "Springfield",
state: "IL",
zip: "62701"
}
},
policyDetails: {
coverageType: "Life Insurance",
coverageAmount: 500000,
premium: 1500,
startDate: new Date("2023-01-01"),
endDate: new Date("2033-01-01")
},
beneficiaries: [
{
name: "Jane Doe",
relationship: "Spouse",
share: 100
}
],
createdAt: new Date()
});
Explanation of the Sample Document:
- policyNumber: A unique identifier for the insurance policy.
- policyHolder: An embedded document containing personal information about the policyholder.
- The address field is a sub-document, which allows you to store nested objects.
- policyDetails: Another embedded document that contains details about the policy (coverage, premium, start and end dates).
- beneficiaries: An array of embedded documents that list the beneficiaries and their share.
- createdAt: A field to record when the document was created.
Step 6: Query the Document
After inserting the document, you can query the data. Here’s how to find the document you just inserted:
db.policies.findOne({ policyNumber: "INS123456" })
This will retrieve the document that matches the policy number INS123456
Step 7: Update the Document
If you want to update a document, you can use the updateOne() or updateMany() methods. For example, to update the coverage amount for a specific policy:
db.policies.updateOne(
{ policyNumber: "INS123456" },
{ $set: { "policyDetails.coverageAmount": 600000 } }
);
Step 8: Delete a Document
To delete a document, you can use the deleteOne() or deleteMany() methods. For example, to delete the insurance policy document:
db.policies.deleteOne({ policyNumber: "INS123456" })
MongoDB Schema Design Considerations
When designing a schema for MongoDB, keep the following considerations in mind:
- Embed documents when data is tightly related: In the example above, we embedded the policyHolder and policyDetails as sub-documents because these fields are part of the insurance policy and are unlikely to be reused separately.
- Use references for loosely related data: If data in one document is referenced by many documents, consider using a reference to another document instead of embedding it.
- Keep scalability in mind: MongoDB is designed to scale horizontally, so ensure your schema can handle large amounts of data by properly designing indexes and using sharding if needed.
Conclusion
MongoDB is a flexible, scalable NoSQL database that uses a document-oriented model to store data. It allows you to store semi-structured or unstructured data in a format that is easy to scale and query. In the example above, we created a simple insurance policy document, inserted it into the database, and demonstrated how to query, update, and delete the document.
MongoDB’s document-based approach provides several advantages over traditional relational databases, particularly for applications with complex, evolving data structures.
Recent Comments