SURVEY ON MONGODB: AN OPEN-SOURCE DOCUMENT DATABASEIAEME Publication
MongoDB is open source cross platform database. It is classified as NoSQL (Not Only SQL). It is written in C++ and it follows document oriented data model. It is database model which provides dynamic schema. It uses features like Map/Reduce, Auto-sharding and MongoDump etc. Using these features MongoDB provides high performance, where Map/Reduce is efficient data arrangement, Auto-sharding is storing data on across the different machines, Backup facilities and many more. It has collections as table and each collection can store different kinds of data. It stores data in JSON like structure. Unlike the RDBMS databases it can store unstructured data as well. It can process and handle large amount of data more efficiently than RDBMS. It is ACID system like RDBMS databases. MongoDB mainly used in such application which produces and uses vast amount of data. Like blogs or sites which produces or stores unstructured data. It can be used to in applications which stores structured and semi-structured data as well.
In my presentation i covered a few thing on NoSQL
What is NoSQL
NoSQL Features
Types of NoSQL
Advantages on NoSQL
and then i moved to MongoDB. This presentation deals with some basic question like
When do we embed data versus linking?
How many collections do we have, and what are they?
When do we need atomic operations?
What indexes will we create to make query and updates fast?
What is shard?
Include or not include? A fairy tale about indexesAlexey Kovaliov
So what is the real-world difference between regular covering indexes and covering indexes with included columns?
Presentation from SqlSaturday 199, Bulgaria, Sofia
Query Analyzing
Introduction into indexes
Indexes In Mongo
Managing indexes in MongoDB
Using index to sort query results.
When should I use indexes.
When should we avoid using indexes.
SURVEY ON MONGODB: AN OPEN-SOURCE DOCUMENT DATABASEIAEME Publication
MongoDB is open source cross platform database. It is classified as NoSQL (Not Only SQL). It is written in C++ and it follows document oriented data model. It is database model which provides dynamic schema. It uses features like Map/Reduce, Auto-sharding and MongoDump etc. Using these features MongoDB provides high performance, where Map/Reduce is efficient data arrangement, Auto-sharding is storing data on across the different machines, Backup facilities and many more. It has collections as table and each collection can store different kinds of data. It stores data in JSON like structure. Unlike the RDBMS databases it can store unstructured data as well. It can process and handle large amount of data more efficiently than RDBMS. It is ACID system like RDBMS databases. MongoDB mainly used in such application which produces and uses vast amount of data. Like blogs or sites which produces or stores unstructured data. It can be used to in applications which stores structured and semi-structured data as well.
In my presentation i covered a few thing on NoSQL
What is NoSQL
NoSQL Features
Types of NoSQL
Advantages on NoSQL
and then i moved to MongoDB. This presentation deals with some basic question like
When do we embed data versus linking?
How many collections do we have, and what are they?
When do we need atomic operations?
What indexes will we create to make query and updates fast?
What is shard?
Include or not include? A fairy tale about indexesAlexey Kovaliov
So what is the real-world difference between regular covering indexes and covering indexes with included columns?
Presentation from SqlSaturday 199, Bulgaria, Sofia
Query Analyzing
Introduction into indexes
Indexes In Mongo
Managing indexes in MongoDB
Using index to sort query results.
When should I use indexes.
When should we avoid using indexes.
eXTend DB. An embedded extensible document database. Extend with custom queries and object modifiers. Learn More ».
Morph DB. A Key-Value pair database. Allows fast in-place updates / object expansion. Learn More ».
Block Manager
An innovative library which manages on-disk blocks inside a file and provides a very simple interface to be used for variety of on-disk datastructures.
http://sscreation.net.in
MongoDB (from humongous) is a cross-platform document-oriented database. Classified as a NoSQL database, MongoDB eschews the traditional table-based relational database structure in favor of JSON-like documents with dynamic schemas (MongoDB calls the format BSON), making the integration of data in certain types of applications easier and faster. Released under a combination of the GNU Affero General Public License and the Apache License, MongoDB is free and open-source software.
MongoDB .local Munich 2019: Managing a Heterogeneous Stack with MongoDB & SQLMongoDB
Data administrators face the challenge of integrating disparate data technologies into a cohesive and performant data platform. This is especially true when using diverse query languages and protocols. This session will focus on how to integrate SQL-aware applications into a MongoDB data platform.
AngularJS is a very powerful JavaScript library. It is used in Single Page Application (SPA) projects. It extends HTML DOM with additional attributes and makes it more responsive to user actions. AngularJS is open source, completely free, and used by thousands of developers around the world. It is licensed under the Apache license version 2.0.
Since its first appearance in 2009, NodeJS has come a long way. Many frameworks have been developed on top of it. These all make our task easy and quick. It is us who need to decide which one to choose? So, here is the list of top 10 NodeJS frameworks that will help you build an awesome application.
MongoDB is a popular NoSQL database. This presentation was delivered during a workshop.
First it talks about NoSQL databases, shift in their design paradigm, focuses a little more on document based NoSQL databases and tries drawing some parallel from SQL databases.
Second part, is for hands-on session of MongoDB using mongo shell. But the slides help very less.
At last it touches advance topics like data replication for disaster recovery and handling big data using map-reduce as well as Sharding.
eXTend DB. An embedded extensible document database. Extend with custom queries and object modifiers. Learn More ».
Morph DB. A Key-Value pair database. Allows fast in-place updates / object expansion. Learn More ».
Block Manager
An innovative library which manages on-disk blocks inside a file and provides a very simple interface to be used for variety of on-disk datastructures.
http://sscreation.net.in
MongoDB (from humongous) is a cross-platform document-oriented database. Classified as a NoSQL database, MongoDB eschews the traditional table-based relational database structure in favor of JSON-like documents with dynamic schemas (MongoDB calls the format BSON), making the integration of data in certain types of applications easier and faster. Released under a combination of the GNU Affero General Public License and the Apache License, MongoDB is free and open-source software.
MongoDB .local Munich 2019: Managing a Heterogeneous Stack with MongoDB & SQLMongoDB
Data administrators face the challenge of integrating disparate data technologies into a cohesive and performant data platform. This is especially true when using diverse query languages and protocols. This session will focus on how to integrate SQL-aware applications into a MongoDB data platform.
AngularJS is a very powerful JavaScript library. It is used in Single Page Application (SPA) projects. It extends HTML DOM with additional attributes and makes it more responsive to user actions. AngularJS is open source, completely free, and used by thousands of developers around the world. It is licensed under the Apache license version 2.0.
Since its first appearance in 2009, NodeJS has come a long way. Many frameworks have been developed on top of it. These all make our task easy and quick. It is us who need to decide which one to choose? So, here is the list of top 10 NodeJS frameworks that will help you build an awesome application.
MongoDB is a popular NoSQL database. This presentation was delivered during a workshop.
First it talks about NoSQL databases, shift in their design paradigm, focuses a little more on document based NoSQL databases and tries drawing some parallel from SQL databases.
Second part, is for hands-on session of MongoDB using mongo shell. But the slides help very less.
At last it touches advance topics like data replication for disaster recovery and handling big data using map-reduce as well as Sharding.
As your data grows, the need to establish proper indexes becomes critical to performance. MongoDB supports a wide range of indexing options to enable fast querying of your data, but what are the right strategies for your application?
In this talk we’ll cover how indexing works, the various indexing options, and use cases where each can be useful. We'll dive into common pitfalls using real-world examples to ensure that you're ready for scale.
MongoDB Basics - An introduction of mongo for beginners.
Covered basic of Indexing, Replicaset, Covered queries, Backup tools and Why we need mongo and some use cases.
In this lecture we analyze document oriented databases. In particular we consider why there are the first approach to nosql and what are the main features. Then, we analyze as example MongoDB. We consider the data model, CRUD operations, write concerns, scaling (replication and sharding).
Finally we presents other document oriented database and when to use or not document oriented databases.
This is an introduction about the MongoDB. It includes basic MongoQueries. Not a advance level of presentation but provide nice information for the starters
Dive deep into the intricacies of MongoDB with our comprehensive presentation on 'Indexing and Query Performance.' Explore essential concepts, from the foundational structure of indexes to advanced techniques for query optimization. With real-world case studies and insightful visualizations, gain a profound understanding of how MongoDB's indexing dramatically impacts the efficiency and speed of data retrieval. Whether you're a novice or an experienced developer, this presentation offers valuable insights to enhance your MongoDB expertise
Operation “Blue Star” is the only event in the history of Independent India where the state went into war with its own people. Even after about 40 years it is not clear if it was culmination of states anger over people of the region, a political game of power or start of dictatorial chapter in the democratic setup.
The people of Punjab felt alienated from main stream due to denial of their just demands during a long democratic struggle since independence. As it happen all over the word, it led to militant struggle with great loss of lives of military, police and civilian personnel. Killing of Indira Gandhi and massacre of innocent Sikhs in Delhi and other India cities was also associated with this movement.
Biological screening of herbal drugs: Introduction and Need for
Phyto-Pharmacological Screening, New Strategies for evaluating
Natural Products, In vitro evaluation techniques for Antioxidants, Antimicrobial and Anticancer drugs. In vivo evaluation techniques
for Anti-inflammatory, Antiulcer, Anticancer, Wound healing, Antidiabetic, Hepatoprotective, Cardio protective, Diuretics and
Antifertility, Toxicity studies as per OECD guidelines
The French Revolution, which began in 1789, was a period of radical social and political upheaval in France. It marked the decline of absolute monarchies, the rise of secular and democratic republics, and the eventual rise of Napoleon Bonaparte. This revolutionary period is crucial in understanding the transition from feudalism to modernity in Europe.
For more information, visit-www.vavaclasses.com
Palestine last event orientationfvgnh .pptxRaedMohamed3
An EFL lesson about the current events in Palestine. It is intended to be for intermediate students who wish to increase their listening skills through a short lesson in power point.
Model Attribute Check Company Auto PropertyCeline George
In Odoo, the multi-company feature allows you to manage multiple companies within a single Odoo database instance. Each company can have its own configurations while still sharing common resources such as products, customers, and suppliers.
Instructions for Submissions thorugh G- Classroom.pptxJheel Barad
This presentation provides a briefing on how to upload submissions and documents in Google Classroom. It was prepared as part of an orientation for new Sainik School in-service teacher trainees. As a training officer, my goal is to ensure that you are comfortable and proficient with this essential tool for managing assignments and fostering student engagement.
Read| The latest issue of The Challenger is here! We are thrilled to announce that our school paper has qualified for the NATIONAL SCHOOLS PRESS CONFERENCE (NSPC) 2024. Thank you for your unwavering support and trust. Dive into the stories that made us stand out!
Synthetic Fiber Construction in lab .pptxPavel ( NSTU)
Synthetic fiber production is a fascinating and complex field that blends chemistry, engineering, and environmental science. By understanding these aspects, students can gain a comprehensive view of synthetic fiber production, its impact on society and the environment, and the potential for future innovations. Synthetic fibers play a crucial role in modern society, impacting various aspects of daily life, industry, and the environment. ynthetic fibers are integral to modern life, offering a range of benefits from cost-effectiveness and versatility to innovative applications and performance characteristics. While they pose environmental challenges, ongoing research and development aim to create more sustainable and eco-friendly alternatives. Understanding the importance of synthetic fibers helps in appreciating their role in the economy, industry, and daily life, while also emphasizing the need for sustainable practices and innovation.
Macroeconomics- Movie Location
This will be used as part of your Personal Professional Portfolio once graded.
Objective:
Prepare a presentation or a paper using research, basic comparative analysis, data organization and application of economic information. You will make an informed assessment of an economic climate outside of the United States to accomplish an entertainment industry objective.
Honest Reviews of Tim Han LMA Course Program.pptxtimhan337
Personal development courses are widely available today, with each one promising life-changing outcomes. Tim Han’s Life Mastery Achievers (LMA) Course has drawn a lot of interest. In addition to offering my frank assessment of Success Insider’s LMA Course, this piece examines the course’s effects via a variety of Tim Han LMA course reviews and Success Insider comments.
Introduction to AI for Nonprofits with Tapp NetworkTechSoup
Dive into the world of AI! Experts Jon Hill and Tareq Monaur will guide you through AI's role in enhancing nonprofit websites and basic marketing strategies, making it easy to understand and apply.
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...Levi Shapiro
Letter from the Congress of the United States regarding Anti-Semitism sent June 3rd to MIT President Sally Kornbluth, MIT Corp Chair, Mark Gorenberg
Dear Dr. Kornbluth and Mr. Gorenberg,
The US House of Representatives is deeply concerned by ongoing and pervasive acts of antisemitic
harassment and intimidation at the Massachusetts Institute of Technology (MIT). Failing to act decisively to ensure a safe learning environment for all students would be a grave dereliction of your responsibilities as President of MIT and Chair of the MIT Corporation.
This Congress will not stand idly by and allow an environment hostile to Jewish students to persist. The House believes that your institution is in violation of Title VI of the Civil Rights Act, and the inability or
unwillingness to rectify this violation through action requires accountability.
Postsecondary education is a unique opportunity for students to learn and have their ideas and beliefs challenged. However, universities receiving hundreds of millions of federal funds annually have denied
students that opportunity and have been hijacked to become venues for the promotion of terrorism, antisemitic harassment and intimidation, unlawful encampments, and in some cases, assaults and riots.
The House of Representatives will not countenance the use of federal funds to indoctrinate students into hateful, antisemitic, anti-American supporters of terrorism. Investigations into campus antisemitism by the Committee on Education and the Workforce and the Committee on Ways and Means have been expanded into a Congress-wide probe across all relevant jurisdictions to address this national crisis. The undersigned Committees will conduct oversight into the use of federal funds at MIT and its learning environment under authorities granted to each Committee.
• The Committee on Education and the Workforce has been investigating your institution since December 7, 2023. The Committee has broad jurisdiction over postsecondary education, including its compliance with Title VI of the Civil Rights Act, campus safety concerns over disruptions to the learning environment, and the awarding of federal student aid under the Higher Education Act.
• The Committee on Oversight and Accountability is investigating the sources of funding and other support flowing to groups espousing pro-Hamas propaganda and engaged in antisemitic harassment and intimidation of students. The Committee on Oversight and Accountability is the principal oversight committee of the US House of Representatives and has broad authority to investigate “any matter” at “any time” under House Rule X.
• The Committee on Ways and Means has been investigating several universities since November 15, 2023, when the Committee held a hearing entitled From Ivory Towers to Dark Corners: Investigating the Nexus Between Antisemitism, Tax-Exempt Universities, and Terror Financing. The Committee followed the hearing with letters to those institutions on January 10, 202
2. Indexes in MongoDB
•
Indexes support the efficient resolution of queries in MongoDB.
–Without indexes, MongoDB must scan every document in a collection to select
those documents that match the query statement.
–These collection scans are inefficient and require the mongod to process a large
volume of data for each operation.
•
Indexes are special data structures that store a small portion of the
collection’s data set in an easy to traverse form.
–The index stores the value of a specific field or set of fields, ordered by the value of
the field.
•
Indexes in MongoDB are similar to indexes in other database systems.
•
MongoDB defines indexes at the collection level and supports indexes on
any field or sub-field of the documents in a MongoDB collection.
3. Indexes in MongoDB..2
•
The following diagram illustrates a query that selects documents using an
index.
MongoDB narrows the query by scanning the range of documents with values of score
less than 30.
4. Indexes in MongoDB..3
•
MongoDB can use indexes to return documents sorted by the index key
directly from the index without requiring an additional sort phase.
Descending
5. Indexes in MongoDB..4
Index Types
• Default _id
–All MongoDB collections have an index on the _id field that exists by default. If
applications do not specify a value for _id the driver or the mongod will create an
_id field with an ObjectID value.
–The _id index is unique, and prevents clients from inserting two documents with
the same value for the _id field.
•
Single Field
–MongoDB supports user-defined indexes on a single field of a document.
Example: Index on score filed (ascending)
6. Indexes in MongoDB..5
Index Types
• Compound Index
–These are user-defined indexes on multiple fields
Example: Diagram of a compound index on the userid field (ascending) and the
score field (descending). The index sorts first by the userid field and then by the
score field.
7. Indexes in MongoDB..6
Index Types
• Multikey Index
–MongoDB uses multikey indexes to index the content stored in arrays.
–If we index a field that holds an array value, MongoDB creates separate index
entries for every element of the array.
–These multikey indexes allow queries to select documents that contain arrays by
matching on element or elements of the arrays.
–MongoDB automatically determines whether to create a multikey index if the
indexed field contains an array value; we do not need to explicitly specify the
multikey type.
8. Indexes in MongoDB..7
Index Types
• Multikey Index: Illustration
Diagram of a multikey index on the addr.zip field.
The addr field contains an array of address
documents. The address documents contain the
zip field.
9. Indexes in MongoDB..8
Other Index Types
• Geospatial Index
–
•
Text Index
–
–
•
MongoDB provides two special indexes: 2d indexes that uses planar geometry
when returning results and 2sphere indexes that use spherical geometry to
return results.
MongoDB provides a beta text index type that supports searching for string
content in a collection.
These text indexes do not store language-specific stop words (e.g. “the”, “a”,
“or”) and stem the words in a collection to only store root words.
Hashed Index
–
To support hash based sharding, MongoDB provides a hashed index type,
which indexes the hash of the value of a field. These indexes have a more
random distribution of values along their range, but only support equality
matches and cannot support range-based queries.
10. Indexes in MongoDB..9
Explicit creation of Index
•
Using ensureIndex() from shell
– The following creates an index on the phone-number field of the people
collection
• db.people.ensureIndex( { "phone-number": 1 } ) .
–
The following operation will create an index on the item, category, and
price fields of the products collection
• db.products.ensureIndex( { item: 1, category: 1, price: 1 } )
–
unique constraint prevent applications from inserting documents that
have duplicate values for the inserted fields. The following example
creates a unique index on the "tax-id": of the accounts collection to
prevent storing multiple account records for the same legal entity
• db.accounts.ensureIndex( { "tax-id": 1 }, { unique: true } )
–
ensureIndex() only creates an index if an index of the same specification
does not already exist.
11. Indexes in MongoDB..10
Indexing Strategies
• Create Indexes to Support Your Queries
–
•
Use Indexes to Sort Query Results
–
•
To support efficient queries, use the strategies here when you specify the
sequential order and sort order of index fields.
Ensure Indexes Fit in RAM
–
•
An index supports a query when the index contains all the fields scanned
by the query. Creating indexes that supports queries results in greatly
increased query performance.
When your index fits in RAM, the system can avoid reading the index from
disk and you get the fastest processing.
Create Queries that Ensure Selectivity
–
Selectivity is the ability of a query to narrow results using the index.
Selectivity allows MongoDB to use the index for a larger portion of the
work associated with fulfilling the query.
12. Indexes in MongoDB..11
•
Indexes to Support Queries
–
–
For commonly issued queries, create indexes. If a query searches multiple
fields, create a compound index. Scanning an index is much faster than
scanning a collection.
Consider a posts collection containing blog posts, and if we need to regularly
issue a query that sorts on the author_name field, then we can optimize the
query by creating an index on the author_name field
• db.posts.ensureIndex( { author_name : 1 } )
–
If we regularly issue a query that sorts on the timestamp field, then we can
optimize the query by creating an index on the timestamp field
• db.posts.ensureIndex( { timestamp : 1 } )
If we want to limit the results to reduce network load, we can use limit()
• db.posts.find().sort( { timestamp : -1 } ).limit(10) [
13. Indexes in MongoDB..12
•
Index Administration
–
–
•
Detailed information about indexes is stored in the system.indexes collection of
each database.
system.indexes is a reserved collection, so we cannot insert documents into it
or remove documents from it. We can manipulate its documents only through
ensureIndex and the dropIndexes database command.
Running Index at Background
–
Building indexes is time-consuming and resource-intensive. Using the
{"background" : true} option builds the index in the background, while handling
incoming requests.
• > db.people.ensureIndex({"username" : 1}, {"background" : true})
–
–
If we do not include the “background” option, the database will block all other
requests while the index is being built.
Creating indexes on existing documents is faster than creating the index first
and then inserting all of the documents.
14. Indexes in MongoDB..12
•
Do’s and Do not’s
–
Create index only on the keys required for the query
• Indexes create additional overhead on the database
• Insert, Update and Delete operations become slow with too many idexes
–
Index direction is important if there are more than one keys
• Index with {"username" : 1, "age" : -1} and {"username" : 1, "age" : 1} have different
connotation
–
–
–
There is a built-in maximum of 64 indexes per collection, which is more than
almost any application should need.
Delete Index with “dropIndexes” if it is not required
Sometimes the most efficient solution is actually not to use an index. In general,
if a query is returning a half or more of the collection, it will be more efficient for
the database to just do a table scan instead of having to look up the index and
then the value for almost every single document.
17. Data Modelling in MongoDB
•
MongoDB has flexible Schema unlike Relational Databases. We need not declare
Table’s schema before inserting data.
•
MongoDB’s collections do not enforce document structure
•
There are 2 ways of mapping Relationships
–References
–Embedded Documents
Example: References
• Both the “contact” and
“access” documents
contain a reference to the
“user” document.
• These are normalized
data models
18. Data Modelling in MongoDB..2
Example: Embedded Documents
“contact” and “access” are subdocuments embedded in main document.
This is a “denormalized” data model
19. Data Modelling in MongoDB..3
References vs. Embedded Documents
References: Used when
Embedded documents: Used when
• embedding would result in
duplication of data but would not
provide sufficient read
performance advantages to
outweigh the implications of the
duplication.
• we have “contains” relationships
between entities.
• to represent more complex manyto-many relationships.
• to model large hierarchical data
sets.
• we have one-to-many relationships
between entities. In these
relationships the “many” or child
documents always appear with or
are viewed in the context of the
“one” or parent documents.
• We need applications to store
related pieces of information in the
same database record.
20. Data Modelling in MongoDB..4
One to many relationships : Example where Embedding is advantageous
Using References
Using Embedded documents
{
{
_id: “chat",
name: "ABC Chat"
_id: "chat",
name: "ABC Chat",
addresses: [
{
street: "10 Simla Street",
city: "Kolkata",
zip: 700006
},
{
street: "132 Lanka Street",
zip: 400032
}
]
}
{
patron_id: "chat",
street: "10 Simla Street",
city: "Kolkata",
zip: 700006
}
{
patron_id: "chat",
street: "132 Lanka Street",
city: "Mumbai",
zip: 400032
}
}
Issue with above: If the application frequently
retrieves the address data with the name
information, then your application needs to
issue multiple queries to resolve the references
With the embedded data model, the application
can retrieve the complete patron information with
one query.
21. Data Modelling in MongoDB..5
One to many relationships : Example where referencing is advantageous
Using Embedded documents
Using Reference
{
{
title: "MongoDB: The Definitive Guide",
author: [ "Kristina Chodorow", "Mike Dirolf" ],
published_date: ISODate("2010-09-24"),
pages: 216,
language: "English",
publisher: {
name: "O'Reilly Media",
location: "CA",
}
_id: "oreilly",
name: "O'Reilly Media",
location: "CA"
}
{
_id: 123456789,
title: "MongoDB: The Definitive Guide",
author: [ "Kristina Chodorow", "Mike Dirolf" ],
published_date: ISODate("2010-09-24"),
pages: 216,
language: "English",
publisher_id: "oreilly"
}
{
title: "50 Tips and Tricks for MongoDB Developer",
author: "Kristina Chodorow",
published_date: ISODate("2011-05-06"),
pages: 68,
language: "English",
publisher: {
name: "O'Reilly Media",
location: "CA",
}
}
{
_id: 234567890,
title: "50 Tips and Tricks for MongoDB Developer",
author: "Kristina Chodorow",
published_date: ISODate("2011-05-06"),
pages: 68,
language: "English",
publisher_id: "oreilly"
}
Issue with above: Embedding leads to
repetition of publisher data.
}
Publisher Information kept separately in the
above example to avoid repetition.
23. Data Modelling in MongoDB..7
Modelling Tree structure with Parent reference
•
The following lines of code describes the tree structure in previous slide
–
–
–
–
–
–
•
db.categories.insert( { _id: "MongoDB", parent: "Databases" } )
db.categories.insert( { _id: “dbm", parent: "Databases" } )
db.categories.insert( { _id: "Databases", parent: "Programming" } )
db.categories.insert( { _id: "Languages", parent: "Programming" } )
db.categories.insert( { _id: "Programming", parent: "Books" } )
db.categories.insert( { _id: "Books", parent: null } )
The query to retrieve the parent of a node
– db.categories.findOne( { _id: "MongoDB" } ).parent;
•
Query by the parent field to find its immediate children nodes
– db.categories.find( { parent: "Databases" } );
24. Data Modelling in MongoDB..8
Modelling Tree structure with Child reference
•
The following lines of code describes the sametree structure
db.categories.insert( { _id: "MongoDB", children: [] } );
db.categories.insert( { _id: “dbm", children: [] } );
db.categories.insert( { _id: "Databases", children: [ "MongoDB", “dbm" ] } );
db.categories.insert( { _id: "Languages", children: [] } )
db.categories.insert( { _id: "Programming", children: [ "Databases",
"Languages" ] } );
– db.categories.insert( { _id: "Books", children: [ "Programming" ] } );
–
–
–
–
–
•
The query to retrieve the immediate child of a node
– db.categories.findOne( { _id: "Databases" } ).children;
•
Query by the child field to find its parent nodes
– db.categories.find( { children: "MongoDB" } );
25. Data Modelling in MongoDB..8
Data Modelling for “Atomic” operations
•
Example (Online purchase portal):
– Step I: Insert data in a collection called “books” including the number of available copies
– Step II: Check if the book is available during checkout
Code
– Step I:
db.book.insert ({
_id: 123456789,
title: "MongoDB: The Definitive Guide",
author: [ "Kristina Chodorow", "Mike Dirolf" ],
published_date: ISODate("2010-09-24"),
pages: 216,
language: "English",
publisher_id: "oreilly",
available: 3,
checkout: [ { by: "joe", date: ISODate("2012-10-15") } ]
});
26. Data Modelling in MongoDB..9
Data Modelling for “Atomic” operations
Code
– Step II
db.book.findAndModify ( {
query: {
_id: 123456789,
available: { $gt: 0 }
},
update: {
$inc: { available: -1 },
$push: { checkout: { by: "abc", date: new Date() } }
}
} );
– In the above example, db.collection.findAndModify() method is used to atomically determine
if a book is available for checkout and update with the new checkout information.
– Embedding the available field and the checkout field within the same document ensures that
the updates to these fields are in sync:
27. Data Modelling in MongoDB..10
Keyword based Search
Example: Perform a keyword based search in a collection “volumes”
– Step I: Insert data in a collection “volumes”
db.volumes.insert ({
title : "Moby-Dick" ,
author : "Herman Melville" ,
published : 1851 ,
ISBN : 0451526996 ,
topics : [ "whaling" , "allegory" , "revenge" , "American" ,
"novel" , "nautical" , "voyage" , "Cape Cod" ]
});
In the above example, several topics are included on which we can perform keyword search
–
Step II: create a multi-key index on the topics array
db.volumes.ensureIndex( { topics: 1 } )
–
Step III: Search based on keyword “voyage”
• db.volumes.findOne( { topics : "voyage" }, { title: 1 } )
28. Exercise
•
•
Create a collection named product meant for albums. The album can have several
product types including Audio Album and Movie.
Record of Audio album can be created with the following attributes
–
–
•
Record 1 (music Album) sku (character, unique identifier), type-Audio Album ,title:”
Remembering Manna De”, description “By Music lovers”, physical_description (weight, width,
height, depth), pricing (list, retail, savings, pct_savings), details (title, artist,genre (“bengali
modern”, “bengali film”), tracks (“birth”, “childhood”, “growing up”, “end”)
Record 2 (movie) with similar details and description pertaining to movie (e.g. director, writer,
music director, actors)
Assignment
–
–
Write a query to return all products with a discount>10%
Write a query which will return the documents for the albums of a specific genre, sorted in
reverse chronological order
–
Write a query which selects films that a particular actor starred in, sorted by issue date