Welcome to this comprehensive guide on No SQL! In this tutorial, we'll dive into the world of Document Stores, a popular type of No SQL database.
Document stores are a type of No SQL database that store data in the form of documents, each with a unique identifier. These documents can have dynamic structures, making them highly flexible and suitable for handling diverse data types.
💡 Pro Tip: Document stores are ideal for applications that require high scalability, real-time data processing, and flexible data structures.
JSON is a lightweight data interchange format that's easy for humans to read and write and easy for machines to parse and generate. It's often used to transmit data between a server and a web application as an alternative to XML.
Unlike traditional relational databases, document stores don't require a predefined schema. This means you can add, remove, or modify properties in your documents as needed, making them highly flexible.
In document stores, you can either embed related data within a single document or reference related documents. Embedding is useful when the related data is frequently accessed, while referencing helps in reducing document size and improving query performance.
MongoDB is one of the most popular document stores. Let's set up a simple MongoDB instance and interact with it.
To install MongoDB, follow the official guide.
After installation, start the MongoDB server and interact with it using the MongoDB Shell. Let's create a collection (a group of documents) named books and add a document.
use mydb # Create or switch to a database named 'mydb'
db.books.insertOne({"title": "The Catcher in the Rye", "author": "J.D. Salinger"})📝 Note: The db object represents the currently selected database, and the books collection is created implicitly when we insert a document into it.
Now that we have some data, let's query it.
db.books.find() # Fetch all documents
db.books.find({"author": "J.D. Salinger"}) # Fetch documents by authorIn this example, we'll embed a book's reviews within the book document.
db.books.updateOne(
{ "title": "The Catcher in the Rye" },
{ $push: { reviews: { "rating": 5, "comment": "Masterpiece!" } } }
)In this example, we'll create a separate reviews collection and reference reviews from our book document.
db.createCollection("reviews")
db.books.updateOne(
{ "title": "The Catcher in the Rye" },
{ $set: { "reviews_id": db.reviews.insertOne({ "review_id": 1, "rating": 5, "comment": "Masterpiece!" }).inserted_id } }
)What is a key concept of document stores?
Happy coding! Stay tuned for more on No SQL and document stores. 🚀