SlideShare ist ein Scribd-Unternehmen logo
1 von 27
MongoDB

{

“by”: “JayaNaresh”,
“e-mail”: “kjayanaresh@yahoo.com”

}
A Brief History…
MongoDB (derived from "humongous") is a cross-platform documentoriented database system. Classified as a NoSQL database, MongoDB avoids
the traditional table-based relational database structure in favor of JSON-like
documents with dynamic schemas (Binary-encoded JSON representation),
making the integration of data in certain types of applications easier and
faster.

First developed by 10gen (now MongoDB Inc.) in October 2007 as a
component of a planned platform as a service product, the company shifted to
an open source development model in 2009, with 10gen offering commercial
support and other services. Since then, MongoDB has been adopted as
backend software by a number of major websites and services, including
Craigslist, eBay, Foursquare, SourceForge, and The New York Times, among
others. MongoDB is the most popular NoSQL database system.

Released under a combination of the GNU Affero General Public License and the Apache License, MongoDB is free and open source
software.
NoSQL

NoSQL is intended as shorthand for "not only SQL."
Complete architectures almost always mix traditional and NoSQL databases.

Brewer's (CAP) Theorem
It's impossible for a distributed computer system to
simultaneously provide all three of these
guarantees:

• Consistency (all nodes see the same data at the
same time)

• Availability (node failures don't prevent
survivors from continuing to operate)

• Partition tolerance (no failures less than total
network failures cause the system to fail)

*NoSQL's primary goal is to achieve horizontal scalability.
It attains this by reducing transactional semantics and
referential integrity.
JSON

JavaScript Object Notation

JSON is a lightweight data-interchange format. It is easy for humans to read and write.
It is easy for machines to parse and generate. It is based on a subset of the JavaScript
Programming Language, Standard ECMA-262 3rd Edition - December 1999. JSON is a
text format that is completely language independent but uses conventions that are
familiar to programmers of the C-family of languages, including C, C++, C#, Java,
JavaScript, Perl Python, and many others. These properties make JSON an ideal datainterchange language.
JSON is built on two structures:
•

A collection of name/value pairs. In
various languages, this is realized
as an
object, record, struct, dictionary, ha
sh table, keyed list, or associative
array.

•

An ordered list of values. In most
languages, this is realized as an
array, vector, list, or sequence.

*Complex Objects in JSON
JSON
•

Objects in JSON

Simple JSON Object:

•
{

{

"firstName": "Jaya Naresh",
"lastName": ”K",
"numberOfPosts": 10,
"friends": [
{
"name": "Siva",
"city": ”Vijayawada",
"posts": 20
},
{
"name": "Ram",
"city": "Hyderabad",
"posts": 15
},
{
"name": "Lakshman",
"city": "Hyderabad",
"posts": 5
}
]

"firstName":"Jaya Naresh",
"lastName": ”k",
"numberOfPosts":10
}

•

Complex JSON Object:

With Arrays:

{
"firstName": "Jaya Naresh",
"lastName": ”K",
"numberOfPosts": 10,
"tags": [
"Music”,
"Movies”,
"Gadgets”
]
}
}
MongoDB
RDBMS

MongoDB

•

Databases

•

Databases

•

Tables

•

Collections

•

Rows

•

Documents

Schema free: No

Schema free: Yes, Dynamic Schema
MongoDB
Traditional RDBMS Table(s) structure

Tables
Master tables

Relationships
•
•
•
•

One-to-One
One-to-Many
Many-to-One
Many-to-Many
MongoDB
Collection(s) Structure in MongoDB

{
"id": 1,
"name": "Jaya Naresh K",
"department": [
{
"id": "D001",
"name": ”Tech"
}
],
"location": [
{
"id": "L001",
"name": ”SFO"
},
{
"id": "L002",
"name": "Hyderabad"
}
]

• Embedded

• Referenced

}

*embedded sample
Naming Rules
Databases
Database names cannot contain “.”, “$”, or “0” (the null character). Names can only contain
characters that can be used on your file system as filenames. Admin, config, and local are
reserved database names (you can store your own data in them, but you should never drop
them).

Collections
Collection names cannot contain “$” or “0”. Names prefixed with “system.” are reserved by
MongoDB and cannot be dropped (even if you created the collection). Dots are often used for
organization in collection names, but they have no semantic importance. A collection named
“che.se” has no more relation to a collection named “che” than one named “cheese” does.

Field Names
Field names cannot contain “.” nor “0”. Fields should only contain “$” when they are
database references.
Insert Documents
•

Save / Insert Function

Both functions does the same functionality

db.collection.save(<document>)
db.collection.insert(<document>)
Command
db.books.save( { item: "Divine Comedy”, price: 18, stock: 5 } )
db.books.insert({
”_id": 1,
"name": "Jaya Naresh K",
"department": [
{
"id": "D001",
"name": “Tech."
}
]
})

•

The _id Field

The _id field has the following behavior and constraints:
1.
2.

In documents, the _id field is always indexed for regular collections.
The _id field may contain values of any BSON data type, other than an array.
Query Operators
•

Query Format

Queries are generally of the form (JSON):
{key : value} or {key : {$op : value}}
For example
{age : 18} or {age : {$gte : 18}}
db.collection.find({age : 18}) or db.collection.findOne({age : 18})
There are three exceptions to this rule: $and, $or, and $nor, which are all top-level:
{$or : [{age: {$gte : 18}}, {age : {$lt : 18}]}
{$and : [{age: 18}}, {age : 19}]},

•

Dot Notation

MongoDB uses the dot notation to access the elements of an array and to access the fields of a subdocument.
To access an element of an array by the zero-based index position, concatenate the array name with the dot (.) and zerobased index position, and enclose in quotes:
'<array>.<index>’
To access a field of a subdocument with dot-notation, concatenate the subdocument name with the dot (.) and the field
name, and enclose in quotes:
'<subdocument>.<field>’
Query Operators
•

Select All Documents in a Collection

An empty query document ({}) selects all documents in the collection:
db.inventory.find( {} )

•

Specify Equality Condition

To specify equality condition, use the query document { <field>: <value> } to select all documents that contain the<field>
with the specified <value>.
The following example retrieves from the inventory collection all documents where the type field has the value snacks:

db.inventory.find( { type: "snacks" } )

•

Specify Conditions Using Query Operators

A query document can use the query operators to specify conditions in a MongoDB query.
The following example selects all documents in the inventory collection where the value of the type field is either 'food'
or 'snacks':
db.inventory.find( { type: { $in: [ 'food', 'snacks' ] } } )

Although you can express this query using the $or operator, use the $in operator rather than the $or operator when
performing equality checks on the same field.
Query Operators
•

Specify AND Conditions

A compound query can specify conditions for more than one field in the collection’s documents. Implicitly, a logical AND
conjunction connects the clauses of a compound query so that the query selects the documents in the collection that match
all the conditions. In the following example, the query document specifies an equality match on the field food and a less
than ($lt) comparison match on the field price:

db.inventory.find( { type: 'food', price: { $lt: 9.95 } } )

•

Specify OR Conditions

Using the $or operator, you can specify a compound query that joins each clause with a logical OR conjunction so that the
query selects the documents in the collection that match at least one condition. In the following example, the query
document selects all documents in the collection where the field qty has a value greater than ($gt) 100 or the value of the
price field is less than ($lt) 9.95:

db.inventory.find(
{ $or: [
{ qty: { $gt: 100 } },
{ price: { $lt: 9.95 } }
]
}
)

• Specify AND as well as OR Conditions
With additional clauses, you can specify precise conditions for matching documents.
In the following example, the compound query document selects all documents in the collection where the value of the
type field is 'food' and either the qty has a value greater than ($gt) 100 or the value of the price field is less than ($lt) 9.95:
db.inventory.find( { type: 'food', $or: [ { qty: { $gt: 100 } },
{ price: { $lt: 9.95 } } ]
})
Query Operators
Subdocuments
When the field holds an embedded document (i.e. subdocument), you can either specify the entire subdocument as the
value of a field, or “reach into” the subdocument using dot notation, to specify values for individual fields in the
subdocument:

•

Exact Match on Subdocument

To specify an equality match on the whole subdocument, use the query document { <field>: <value> } where <value> is the
subdocument to match. Equality matches on a subdocument require that the subdocument field match exactly the
specified<value>, including the field order. In the following example, the query matches all documents where the value of
the field producer is a subdocument that containsonly the field company with the value 'ABC123' and the field address
with the value '123 Street', in the exact order:
db.inventory.find(
{
producer: {
company: 'ABC123',
address: '123 Street'
}
}
)

• Equality Match on Fields within Subdocument
Equality matches for specific fields within subdocuments select the documents in the collection when the field in the
subdocument contains a field that matches the specified value. In the following example, the query uses the dot notation
to match all documents where the value of the field producer is a subdocument that contains a field company with the
value 'ABC123' and may contain other fields:
db.inventory.find( { 'producer.company': 'ABC123' } )
Query Operators
Arrays
When the field holds an array, you can query for an exact array match or for specific values in the array. If the array holds
sub-documents, you can query for specific fields within the sub-documents using dot notation:

•

Exact Match on an Array

To specify equality match on an array, use the query document { <field>: <value> } where <value> is the array to match.
Equality matches on the array require that the array field match exactly the specified <value>, including the element order.
In the following example, the query matches all documents where the value of the field tags is an array that holds exactly
three elements, 'fruit', 'food', and 'citrus', in this order:
db.inventory.find( { tags: [ 'fruit', 'food', 'citrus' ] } )

•

Match an Array Element

Equality matches can specify a single element in the array to match. These specifications match if the array contains at least
oneelement with the specified value.
In the following example, the query matches all documents where the value of the field tags is an array that contains 'fruit'
as one of its elements:
db.inventory.find( { tags: 'fruit' } )

•

Match a Specific Element of an Array

Equality matches can specify equality matches for an element at a particular index or position of the array.
In the following example, the query uses the dot notation to match all documents where the value of the tags field is an
array whose first element equals 'fruit':
db.inventory.find( { 'tags.0' : 'fruit' } )
Query Operators
Query Selectors
•

Comparison

Name
$gt
$gte
$in
$lt
$lte
$ne
$nin
•

Description
Matches values that are greater than the value specified in the query.
Matches values that are equal to or greater than the value specified in the query.
Matches any of the values that exist in an array specified in the query.
Matches values that are less than the value specified in the query.
Matches values that are less than or equal to the value specified in the query.
Matches all values that are not equal to the value specified in the query.
Matches values that do not exist in an array specified to the query.

Logical

Name
$or
$and
$not

$nor

Description
Joins query clauses with a logical OR returns all documents that match the conditions of either
clause.
Joins query clauses with a logical AND returns all documents that match the conditions of both
clauses.
Inverts the effect of a query expression and returns documents that do not match the query
expression.
Joins query clauses with a logical NOR returns all documents that fail to match both clauses.
Query Operators and Projection Operators
Query Selectors
•

Evaluation

Name
$mod
$regex
$where

•

Description
Performs a modulo operation on the value of a field and selects documents with a
specified result.
Selects documents where values match a specified regular expression.
Matches documents that satisfy a JavaScript expression.

Array

Name
$all
$elemMatch
$size

Description
Matches arrays that contain all elements specified in the query.
Selects documents if element in the array field matches all the specified
$elemMatch condition.
Returns documents if the array field is a specified size.
Query Operators and Projection Operators
Query Selectors
•

Geospatial

Name
$geoWithin
$geoIntersects
$near
$nearSphere

•

Description
Selects geometries within a bounding GeoJSON geometry.
Selects geometries that intersect with a GeoJSON geometry.
eturns geospatial objects in proximity to a point.
Returns geospatial objects in proximity to a point on a sphere.

Projection Operators

Name
$
$elemMatch
$slice

Description
Projects the first element in an array that matches the query condition.
Projects only the first element from an array that matches the specified $elemMatch
condition.
Limits the number of elements projected from an array.
Supports skip and limit slices.
Update Documents
• Update Operators
Fields
Name
$inc
$rename
$setOnInsert
$set
$unset

Description
Increments the value of the field by the specified amount.
Renames a field.
Sets the value of a field upon document creation during an upsert. Has no effect on
update operations that modify existing documents.
Sets the value of a field in an existing document.
Removes the specified field from an existing document.
Update Documents
•

Update Function

db.collection.update( <query>, <update>, { upsert: <boolean>, multi: <boolean> } )

Sample
db.books.update( { item: "Divine Comedy" }, {

$set: { price: 18 },

$inc: { stock: 5 } } )

• Add New Fields
If the <update> parameter contains fields not currently in the document, the update() method adds
the new fields to the document. The following operation adds two new fields: mbranch and aka.
The operation adds aka in the subdocument name:
db.bios.update( { _id: 3 }, { $set: { mbranch: "Navy”, "name.aka": "Amazing Grace” } } )

•

Remove Fields

The following operation uses the $unset operator to remove the birth field from the document that
has _id equal to 3:
db.bios.update( { _id: 3 }, { $unset: { birth: 1 } } )
Update Documents
• Insert a New Document if No Match Exists (Upsert)
The following command sets the upsert option to true so that update() creates a new document in the
books collection if no document matches the <query> parameter:
db.books.update( { item: "The New Life" },
{ item: "The New Life",
author: "Dante",
price: 15 },
{ upsert: true }
)

• Update Multiple Documents
To update multiple documents, set the multi option to true. The following example queries the bios
collection for all documents where awards.award is set to Turing. The update sets the turing field to true:
db.bios.update(
{ "awards.award": "Turing" },
{ $set: { turing: true } },
{ multi: true }
)

• Combine the Upsert and Multi Parameters
db.books.update( { author: "Dante" },
{ $set: { born: "Florence", died: "Ravenna" } },
{ upsert: true, multi: true }
)
Update Arrays
•

Operators

Name
$
update.
$addToSet
$pop
$pullAll
$pull
$pushAll
$push

•

Description
Acts as a placeholder to update the first element that matches the query condition in an
Adds elements to an existing array only if they do not already exist in the set.
Removes the first or last item of an array.
Removes all matching values from an array.
Removes items from an array that match a query statement.
Deprecated. Adds several items to an array.
Adds an item to an array.

Modifiers

Name
$each
$slice
$sort

Description
Modifies the $push and $addToSet operators to append multiple items for array updates.
Modifies the $push operator to limit the size of updated arrays.
Modifies the $push operator to reorder documents stored in an array.

More @ http://docs.mongodb.org/manual/reference/operator/update/
Update Arrays
• Update an Element by Position
If the update operation requires an update of an element in an array field, the update() method can
perform the update using the position of the element and dot notation. Arrays in MongoDB are zerobased.
The following operation queries the bios collection for the first document with _id field equal to 1 and
updates the second element in the contribs array:
db.bios.update(
{ _id: 1 },
{ $set: { "contribs.1": "ALGOL 58" } }
)

• Update an Element if Position is Unknown
If the position in the array is not known, the update() method can perform the update using the $
positional operator. The array field must appear in the <query> parameter in order to determine which
array element to update.
The following operation queries the bios collection for the first document where the _id field equals 3 and
the contribs array contains an element equal to compiler. If found, the update() method updates the first
matching element in the array to A compiler in the document:
db.bios.update(
{ _id: 3, "contribs": "compiler" },
{ $set: { "contribs.$": "A compiler" } }
)
Update Arrays
• Update a Document Element
The update() method can perform the update of an array that contains subdocuments by using the
positional operator (i.e. $) and the dot notation.
The following operation queries the bios collection for the first document where the _id field equals 6 and
the awards array contains a subdocument element with the by field equal to ACM. If found, the update()
method updates the by field in the first matching subdocument:
db.bios.update(
{ _id: 6, "awards.by": "ACM" } ,
{ $set: { "awards.$.by": "Association for Computing Machinery" } }
)

• Add an Element
The following operation queries the bios collection for the first document that has an _id field equal to 1
and adds a new element to the awards field:
db.bios.update(
{ _id: 1 },
{
$push: { awards: { award: "IBM Fellow", year: 1963, by: "IBM" } }
}
)
Mongo Shell Methods
JavaScript in MongoDB Although these methods use JavaScript, most interactions with MongoDB do not use JavaScript but use an
idiomatic driver in the language of the interacting application.

Collection Functions
Name

Description

db.collection.aggregate()

Provides access to the aggregation pipeline.

db.collection.distinct()

Returns an array of documents that have distinct values for the specified field.

db.collection.drop()

Removes the specified collection from the database.

db.collection.dropIndex()

Removes a specified index on a collection.

db.collection.dropIndexes()

Removes all indexes on a collection.

db.collection.ensureIndex()

Creates an index if it does not currently exist. If the index existsensureIndex() does

nothing.
db.collection.find()

Performs a query on a collection and returns a cursor object.

db.collection.findAndModify()

Atomically modifies and returns a single document.

db.collection.findOne()

Performs a query and returns a single document.

db.collection.getIndexes()

Returns an array of documents that describe the existing indexes on a collection.

db.collection.group()

Provides simple data aggregation function. Groups documents in a collection by a key, and
processes the results. Use aggregate() for more complex data aggregation.

db.collection.insert()

Creates a new document in a collection.

db.collection.mapReduce()

erforms map-reduce style data aggregation.

db.collection.reIndex()

Rebuilds all existing indexes on a collection.

db.collection.remove()

Deletes documents from a collection.

db.collection.renameCollection()

Changes the name of a collection.

db.collection.save()

Provides a wrapper around an insert() and update() to insert new documents.

db.collection.update()

Modifies a document in a collection.
Mongo Shell Methods
Cursor Functions
Name

Description

cursor.count()

Returns a count of the documents in a cursor.

cursor.explain()

Reports on the query execution plan, including index use, for a cursor.

cursor.hint()

Forces MongoDB to use a specific index for a query.

cursor.limit()

Constrains the size of a cursor’s result set.

cursor.map()

Applies a function to each document in a cursor and collects the return values in an array.

cursor.max()

Specifies an exclusive upper index bound for a cursor. For use with cursor.hint()

cursor.min()

Specifies an inclusive lower index bound for a cursor. For use with cursor.hint()

cursor.next()

Returns the next document in a cursor.

cursor.size()

Returns a count of the documents in the cursor after applying skip() and limit()methods.

cursor.skip()

Returns a cursor that begins returning results only after passing or skipping a number
of documents.

cursor.sort()

Returns results ordered according to a sort specification.

cursor.toArray()

Returns an array that contains all documents returned by the cursor.

More shell functions @ http://docs.mongodb.org/manual/reference/method/
RefCardz

Weitere ähnliche Inhalte

Was ist angesagt?

Mongodb basics and architecture
Mongodb basics and architectureMongodb basics and architecture
Mongodb basics and architectureBishal Khanal
 
MongoDB Fundamentals
MongoDB FundamentalsMongoDB Fundamentals
MongoDB FundamentalsMongoDB
 
Indexing with MongoDB
Indexing with MongoDBIndexing with MongoDB
Indexing with MongoDBMongoDB
 
Introduction to MongoDB.pptx
Introduction to MongoDB.pptxIntroduction to MongoDB.pptx
Introduction to MongoDB.pptxSurya937648
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDBMike Dirolf
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDBMongoDB
 
An introduction to MongoDB
An introduction to MongoDBAn introduction to MongoDB
An introduction to MongoDBCĂ©sar Trigo
 
Mongo Nosql CRUD Operations
Mongo Nosql CRUD OperationsMongo Nosql CRUD Operations
Mongo Nosql CRUD Operationsanujaggarwal49
 
Mongodb - NoSql Database
Mongodb - NoSql DatabaseMongodb - NoSql Database
Mongodb - NoSql DatabasePrashant Gupta
 
Introduction to elasticsearch
Introduction to elasticsearchIntroduction to elasticsearch
Introduction to elasticsearchpmanvi
 
MongodB Internals
MongodB InternalsMongodB Internals
MongodB InternalsNorberto Leite
 
An Enterprise Architect's View of MongoDB
An Enterprise Architect's View of MongoDBAn Enterprise Architect's View of MongoDB
An Enterprise Architect's View of MongoDBMongoDB
 
Elasticsearch for beginners
Elasticsearch for beginnersElasticsearch for beginners
Elasticsearch for beginnersNeil Baker
 

Was ist angesagt? (20)

MongoDB 101
MongoDB 101MongoDB 101
MongoDB 101
 
Mongodb basics and architecture
Mongodb basics and architectureMongodb basics and architecture
Mongodb basics and architecture
 
MongoDB
MongoDBMongoDB
MongoDB
 
MongoDB Fundamentals
MongoDB FundamentalsMongoDB Fundamentals
MongoDB Fundamentals
 
An introduction to MongoDB
An introduction to MongoDBAn introduction to MongoDB
An introduction to MongoDB
 
Indexing with MongoDB
Indexing with MongoDBIndexing with MongoDB
Indexing with MongoDB
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 
Introduction to MongoDB.pptx
Introduction to MongoDB.pptxIntroduction to MongoDB.pptx
Introduction to MongoDB.pptx
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 
An introduction to MongoDB
An introduction to MongoDBAn introduction to MongoDB
An introduction to MongoDB
 
Mongo db intro.pptx
Mongo db intro.pptxMongo db intro.pptx
Mongo db intro.pptx
 
Mongo Nosql CRUD Operations
Mongo Nosql CRUD OperationsMongo Nosql CRUD Operations
Mongo Nosql CRUD Operations
 
Mongodb - NoSql Database
Mongodb - NoSql DatabaseMongodb - NoSql Database
Mongodb - NoSql Database
 
Mongodb
MongodbMongodb
Mongodb
 
Introduction to elasticsearch
Introduction to elasticsearchIntroduction to elasticsearch
Introduction to elasticsearch
 
MongodB Internals
MongodB InternalsMongodB Internals
MongodB Internals
 
MongoDB (Advanced)
MongoDB (Advanced)MongoDB (Advanced)
MongoDB (Advanced)
 
An Enterprise Architect's View of MongoDB
An Enterprise Architect's View of MongoDBAn Enterprise Architect's View of MongoDB
An Enterprise Architect's View of MongoDB
 
Elasticsearch for beginners
Elasticsearch for beginnersElasticsearch for beginners
Elasticsearch for beginners
 

Ă„hnlich wie Mongo DB Presentation

Mongo db basics
Mongo db basicsMongo db basics
Mongo db basicsDhaval Mistry
 
MongoDB Aggregation Framework
MongoDB Aggregation FrameworkMongoDB Aggregation Framework
MongoDB Aggregation FrameworkCaserta
 
Mongo db queries
Mongo db queriesMongo db queries
Mongo db queriesssuser6d5faa
 
NOSQL and MongoDB Database
NOSQL and MongoDB DatabaseNOSQL and MongoDB Database
NOSQL and MongoDB DatabaseTariqul islam
 
Introduction to MongoDB and Workshop
Introduction to MongoDB and WorkshopIntroduction to MongoDB and Workshop
Introduction to MongoDB and WorkshopAhmedabadJavaMeetup
 
10gen Presents Schema Design and Data Modeling
10gen Presents Schema Design and Data Modeling10gen Presents Schema Design and Data Modeling
10gen Presents Schema Design and Data ModelingDATAVERSITY
 
MongoDB.local DC 2018: Tutorial - Data Analytics with MongoDB
MongoDB.local DC 2018: Tutorial - Data Analytics with MongoDBMongoDB.local DC 2018: Tutorial - Data Analytics with MongoDB
MongoDB.local DC 2018: Tutorial - Data Analytics with MongoDBMongoDB
 
Basics of JSON (JavaScript Object Notation) with examples
Basics of JSON (JavaScript Object Notation) with examplesBasics of JSON (JavaScript Object Notation) with examples
Basics of JSON (JavaScript Object Notation) with examplesSanjeev Kumar Jaiswal
 
EinfĂĽhrung in MongoDB
EinfĂĽhrung in MongoDBEinfĂĽhrung in MongoDB
EinfĂĽhrung in MongoDBNETUserGroupBern
 
3-Mongodb and Mapreduce Programming.pdf
3-Mongodb and Mapreduce Programming.pdf3-Mongodb and Mapreduce Programming.pdf
3-Mongodb and Mapreduce Programming.pdfMarianJRuben
 
Spray Json and MongoDB Queries: Insights and Simple Tricks.
Spray Json and MongoDB Queries: Insights and Simple Tricks.Spray Json and MongoDB Queries: Insights and Simple Tricks.
Spray Json and MongoDB Queries: Insights and Simple Tricks.Andrii Lashchenko
 
Indexing and Query Optimizer
Indexing and Query OptimizerIndexing and Query Optimizer
Indexing and Query OptimizerMongoDB
 
Benjamin Guinebertière - Microsoft Azure: Document DB and other noSQL databas...
Benjamin Guinebertière - Microsoft Azure: Document DB and other noSQL databas...Benjamin Guinebertière - Microsoft Azure: Document DB and other noSQL databas...
Benjamin Guinebertière - Microsoft Azure: Document DB and other noSQL databas...NoSQLmatters
 

Ă„hnlich wie Mongo DB Presentation (20)

Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 
Query Optimization in MongoDB
Query Optimization in MongoDBQuery Optimization in MongoDB
Query Optimization in MongoDB
 
Mongo db basics
Mongo db basicsMongo db basics
Mongo db basics
 
lecture_34e.pptx
lecture_34e.pptxlecture_34e.pptx
lecture_34e.pptx
 
MongoDB
MongoDBMongoDB
MongoDB
 
MongoDB Aggregation Framework
MongoDB Aggregation FrameworkMongoDB Aggregation Framework
MongoDB Aggregation Framework
 
MongoDB
MongoDBMongoDB
MongoDB
 
Mongo db
Mongo dbMongo db
Mongo db
 
Mongodb Introduction
Mongodb IntroductionMongodb Introduction
Mongodb Introduction
 
Mongo db queries
Mongo db queriesMongo db queries
Mongo db queries
 
NOSQL and MongoDB Database
NOSQL and MongoDB DatabaseNOSQL and MongoDB Database
NOSQL and MongoDB Database
 
Introduction to MongoDB and Workshop
Introduction to MongoDB and WorkshopIntroduction to MongoDB and Workshop
Introduction to MongoDB and Workshop
 
10gen Presents Schema Design and Data Modeling
10gen Presents Schema Design and Data Modeling10gen Presents Schema Design and Data Modeling
10gen Presents Schema Design and Data Modeling
 
MongoDB.local DC 2018: Tutorial - Data Analytics with MongoDB
MongoDB.local DC 2018: Tutorial - Data Analytics with MongoDBMongoDB.local DC 2018: Tutorial - Data Analytics with MongoDB
MongoDB.local DC 2018: Tutorial - Data Analytics with MongoDB
 
Basics of JSON (JavaScript Object Notation) with examples
Basics of JSON (JavaScript Object Notation) with examplesBasics of JSON (JavaScript Object Notation) with examples
Basics of JSON (JavaScript Object Notation) with examples
 
EinfĂĽhrung in MongoDB
EinfĂĽhrung in MongoDBEinfĂĽhrung in MongoDB
EinfĂĽhrung in MongoDB
 
3-Mongodb and Mapreduce Programming.pdf
3-Mongodb and Mapreduce Programming.pdf3-Mongodb and Mapreduce Programming.pdf
3-Mongodb and Mapreduce Programming.pdf
 
Spray Json and MongoDB Queries: Insights and Simple Tricks.
Spray Json and MongoDB Queries: Insights and Simple Tricks.Spray Json and MongoDB Queries: Insights and Simple Tricks.
Spray Json and MongoDB Queries: Insights and Simple Tricks.
 
Indexing and Query Optimizer
Indexing and Query OptimizerIndexing and Query Optimizer
Indexing and Query Optimizer
 
Benjamin Guinebertière - Microsoft Azure: Document DB and other noSQL databas...
Benjamin Guinebertière - Microsoft Azure: Document DB and other noSQL databas...Benjamin Guinebertière - Microsoft Azure: Document DB and other noSQL databas...
Benjamin Guinebertière - Microsoft Azure: Document DB and other noSQL databas...
 

KĂĽrzlich hochgeladen

MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 

KĂĽrzlich hochgeladen (20)

MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 

Mongo DB Presentation

  • 2. A Brief History… MongoDB (derived from "humongous") is a cross-platform documentoriented database system. Classified as a NoSQL database, MongoDB avoids the traditional table-based relational database structure in favor of JSON-like documents with dynamic schemas (Binary-encoded JSON representation), making the integration of data in certain types of applications easier and faster. First developed by 10gen (now MongoDB Inc.) in October 2007 as a component of a planned platform as a service product, the company shifted to an open source development model in 2009, with 10gen offering commercial support and other services. Since then, MongoDB has been adopted as backend software by a number of major websites and services, including Craigslist, eBay, Foursquare, SourceForge, and The New York Times, among others. MongoDB is the most popular NoSQL database system. Released under a combination of the GNU Affero General Public License and the Apache License, MongoDB is free and open source software.
  • 3. NoSQL NoSQL is intended as shorthand for "not only SQL." Complete architectures almost always mix traditional and NoSQL databases. Brewer's (CAP) Theorem It's impossible for a distributed computer system to simultaneously provide all three of these guarantees: • Consistency (all nodes see the same data at the same time) • Availability (node failures don't prevent survivors from continuing to operate) • Partition tolerance (no failures less than total network failures cause the system to fail) *NoSQL's primary goal is to achieve horizontal scalability. It attains this by reducing transactional semantics and referential integrity.
  • 4. JSON JavaScript Object Notation JSON is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl Python, and many others. These properties make JSON an ideal datainterchange language. JSON is built on two structures: • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, ha sh table, keyed list, or associative array. • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence. *Complex Objects in JSON
  • 5. JSON • Objects in JSON Simple JSON Object: • { { "firstName": "Jaya Naresh", "lastName": ”K", "numberOfPosts": 10, "friends": [ { "name": "Siva", "city": ”Vijayawada", "posts": 20 }, { "name": "Ram", "city": "Hyderabad", "posts": 15 }, { "name": "Lakshman", "city": "Hyderabad", "posts": 5 } ] "firstName":"Jaya Naresh", "lastName": ”k", "numberOfPosts":10 } • Complex JSON Object: With Arrays: { "firstName": "Jaya Naresh", "lastName": ”K", "numberOfPosts": 10, "tags": [ "Music”, "Movies”, "Gadgets” ] } }
  • 7. MongoDB Traditional RDBMS Table(s) structure Tables Master tables Relationships • • • • One-to-One One-to-Many Many-to-One Many-to-Many
  • 8. MongoDB Collection(s) Structure in MongoDB { "id": 1, "name": "Jaya Naresh K", "department": [ { "id": "D001", "name": ”Tech" } ], "location": [ { "id": "L001", "name": ”SFO" }, { "id": "L002", "name": "Hyderabad" } ] • Embedded • Referenced } *embedded sample
  • 9. Naming Rules Databases Database names cannot contain “.”, “$”, or “0” (the null character). Names can only contain characters that can be used on your file system as filenames. Admin, config, and local are reserved database names (you can store your own data in them, but you should never drop them). Collections Collection names cannot contain “$” or “0”. Names prefixed with “system.” are reserved by MongoDB and cannot be dropped (even if you created the collection). Dots are often used for organization in collection names, but they have no semantic importance. A collection named “che.se” has no more relation to a collection named “che” than one named “cheese” does. Field Names Field names cannot contain “.” nor “0”. Fields should only contain “$” when they are database references.
  • 10. Insert Documents • Save / Insert Function Both functions does the same functionality db.collection.save(<document>) db.collection.insert(<document>) Command db.books.save( { item: "Divine Comedy”, price: 18, stock: 5 } ) db.books.insert({ ”_id": 1, "name": "Jaya Naresh K", "department": [ { "id": "D001", "name": “Tech." } ] }) • The _id Field The _id field has the following behavior and constraints: 1. 2. In documents, the _id field is always indexed for regular collections. The _id field may contain values of any BSON data type, other than an array.
  • 11. Query Operators • Query Format Queries are generally of the form (JSON): {key : value} or {key : {$op : value}} For example {age : 18} or {age : {$gte : 18}} db.collection.find({age : 18}) or db.collection.findOne({age : 18}) There are three exceptions to this rule: $and, $or, and $nor, which are all top-level: {$or : [{age: {$gte : 18}}, {age : {$lt : 18}]} {$and : [{age: 18}}, {age : 19}]}, • Dot Notation MongoDB uses the dot notation to access the elements of an array and to access the fields of a subdocument. To access an element of an array by the zero-based index position, concatenate the array name with the dot (.) and zerobased index position, and enclose in quotes: '<array>.<index>’ To access a field of a subdocument with dot-notation, concatenate the subdocument name with the dot (.) and the field name, and enclose in quotes: '<subdocument>.<field>’
  • 12. Query Operators • Select All Documents in a Collection An empty query document ({}) selects all documents in the collection: db.inventory.find( {} ) • Specify Equality Condition To specify equality condition, use the query document { <field>: <value> } to select all documents that contain the<field> with the specified <value>. The following example retrieves from the inventory collection all documents where the type field has the value snacks: db.inventory.find( { type: "snacks" } ) • Specify Conditions Using Query Operators A query document can use the query operators to specify conditions in a MongoDB query. The following example selects all documents in the inventory collection where the value of the type field is either 'food' or 'snacks': db.inventory.find( { type: { $in: [ 'food', 'snacks' ] } } ) Although you can express this query using the $or operator, use the $in operator rather than the $or operator when performing equality checks on the same field.
  • 13. Query Operators • Specify AND Conditions A compound query can specify conditions for more than one field in the collection’s documents. Implicitly, a logical AND conjunction connects the clauses of a compound query so that the query selects the documents in the collection that match all the conditions. In the following example, the query document specifies an equality match on the field food and a less than ($lt) comparison match on the field price: db.inventory.find( { type: 'food', price: { $lt: 9.95 } } ) • Specify OR Conditions Using the $or operator, you can specify a compound query that joins each clause with a logical OR conjunction so that the query selects the documents in the collection that match at least one condition. In the following example, the query document selects all documents in the collection where the field qty has a value greater than ($gt) 100 or the value of the price field is less than ($lt) 9.95: db.inventory.find( { $or: [ { qty: { $gt: 100 } }, { price: { $lt: 9.95 } } ] } ) • Specify AND as well as OR Conditions With additional clauses, you can specify precise conditions for matching documents. In the following example, the compound query document selects all documents in the collection where the value of the type field is 'food' and either the qty has a value greater than ($gt) 100 or the value of the price field is less than ($lt) 9.95: db.inventory.find( { type: 'food', $or: [ { qty: { $gt: 100 } }, { price: { $lt: 9.95 } } ] })
  • 14. Query Operators Subdocuments When the field holds an embedded document (i.e. subdocument), you can either specify the entire subdocument as the value of a field, or “reach into” the subdocument using dot notation, to specify values for individual fields in the subdocument: • Exact Match on Subdocument To specify an equality match on the whole subdocument, use the query document { <field>: <value> } where <value> is the subdocument to match. Equality matches on a subdocument require that the subdocument field match exactly the specified<value>, including the field order. In the following example, the query matches all documents where the value of the field producer is a subdocument that containsonly the field company with the value 'ABC123' and the field address with the value '123 Street', in the exact order: db.inventory.find( { producer: { company: 'ABC123', address: '123 Street' } } ) • Equality Match on Fields within Subdocument Equality matches for specific fields within subdocuments select the documents in the collection when the field in the subdocument contains a field that matches the specified value. In the following example, the query uses the dot notation to match all documents where the value of the field producer is a subdocument that contains a field company with the value 'ABC123' and may contain other fields: db.inventory.find( { 'producer.company': 'ABC123' } )
  • 15. Query Operators Arrays When the field holds an array, you can query for an exact array match or for specific values in the array. If the array holds sub-documents, you can query for specific fields within the sub-documents using dot notation: • Exact Match on an Array To specify equality match on an array, use the query document { <field>: <value> } where <value> is the array to match. Equality matches on the array require that the array field match exactly the specified <value>, including the element order. In the following example, the query matches all documents where the value of the field tags is an array that holds exactly three elements, 'fruit', 'food', and 'citrus', in this order: db.inventory.find( { tags: [ 'fruit', 'food', 'citrus' ] } ) • Match an Array Element Equality matches can specify a single element in the array to match. These specifications match if the array contains at least oneelement with the specified value. In the following example, the query matches all documents where the value of the field tags is an array that contains 'fruit' as one of its elements: db.inventory.find( { tags: 'fruit' } ) • Match a Specific Element of an Array Equality matches can specify equality matches for an element at a particular index or position of the array. In the following example, the query uses the dot notation to match all documents where the value of the tags field is an array whose first element equals 'fruit': db.inventory.find( { 'tags.0' : 'fruit' } )
  • 16. Query Operators Query Selectors • Comparison Name $gt $gte $in $lt $lte $ne $nin • Description Matches values that are greater than the value specified in the query. Matches values that are equal to or greater than the value specified in the query. Matches any of the values that exist in an array specified in the query. Matches values that are less than the value specified in the query. Matches values that are less than or equal to the value specified in the query. Matches all values that are not equal to the value specified in the query. Matches values that do not exist in an array specified to the query. Logical Name $or $and $not $nor Description Joins query clauses with a logical OR returns all documents that match the conditions of either clause. Joins query clauses with a logical AND returns all documents that match the conditions of both clauses. Inverts the effect of a query expression and returns documents that do not match the query expression. Joins query clauses with a logical NOR returns all documents that fail to match both clauses.
  • 17. Query Operators and Projection Operators Query Selectors • Evaluation Name $mod $regex $where • Description Performs a modulo operation on the value of a field and selects documents with a specified result. Selects documents where values match a specified regular expression. Matches documents that satisfy a JavaScript expression. Array Name $all $elemMatch $size Description Matches arrays that contain all elements specified in the query. Selects documents if element in the array field matches all the specified $elemMatch condition. Returns documents if the array field is a specified size.
  • 18. Query Operators and Projection Operators Query Selectors • Geospatial Name $geoWithin $geoIntersects $near $nearSphere • Description Selects geometries within a bounding GeoJSON geometry. Selects geometries that intersect with a GeoJSON geometry. eturns geospatial objects in proximity to a point. Returns geospatial objects in proximity to a point on a sphere. Projection Operators Name $ $elemMatch $slice Description Projects the first element in an array that matches the query condition. Projects only the first element from an array that matches the specified $elemMatch condition. Limits the number of elements projected from an array. Supports skip and limit slices.
  • 19. Update Documents • Update Operators Fields Name $inc $rename $setOnInsert $set $unset Description Increments the value of the field by the specified amount. Renames a field. Sets the value of a field upon document creation during an upsert. Has no effect on update operations that modify existing documents. Sets the value of a field in an existing document. Removes the specified field from an existing document.
  • 20. Update Documents • Update Function db.collection.update( <query>, <update>, { upsert: <boolean>, multi: <boolean> } ) Sample db.books.update( { item: "Divine Comedy" }, { $set: { price: 18 }, $inc: { stock: 5 } } ) • Add New Fields If the <update> parameter contains fields not currently in the document, the update() method adds the new fields to the document. The following operation adds two new fields: mbranch and aka. The operation adds aka in the subdocument name: db.bios.update( { _id: 3 }, { $set: { mbranch: "Navy”, "name.aka": "Amazing Grace” } } ) • Remove Fields The following operation uses the $unset operator to remove the birth field from the document that has _id equal to 3: db.bios.update( { _id: 3 }, { $unset: { birth: 1 } } )
  • 21. Update Documents • Insert a New Document if No Match Exists (Upsert) The following command sets the upsert option to true so that update() creates a new document in the books collection if no document matches the <query> parameter: db.books.update( { item: "The New Life" }, { item: "The New Life", author: "Dante", price: 15 }, { upsert: true } ) • Update Multiple Documents To update multiple documents, set the multi option to true. The following example queries the bios collection for all documents where awards.award is set to Turing. The update sets the turing field to true: db.bios.update( { "awards.award": "Turing" }, { $set: { turing: true } }, { multi: true } ) • Combine the Upsert and Multi Parameters db.books.update( { author: "Dante" }, { $set: { born: "Florence", died: "Ravenna" } }, { upsert: true, multi: true } )
  • 22. Update Arrays • Operators Name $ update. $addToSet $pop $pullAll $pull $pushAll $push • Description Acts as a placeholder to update the first element that matches the query condition in an Adds elements to an existing array only if they do not already exist in the set. Removes the first or last item of an array. Removes all matching values from an array. Removes items from an array that match a query statement. Deprecated. Adds several items to an array. Adds an item to an array. Modifiers Name $each $slice $sort Description Modifies the $push and $addToSet operators to append multiple items for array updates. Modifies the $push operator to limit the size of updated arrays. Modifies the $push operator to reorder documents stored in an array. More @ http://docs.mongodb.org/manual/reference/operator/update/
  • 23. Update Arrays • Update an Element by Position If the update operation requires an update of an element in an array field, the update() method can perform the update using the position of the element and dot notation. Arrays in MongoDB are zerobased. The following operation queries the bios collection for the first document with _id field equal to 1 and updates the second element in the contribs array: db.bios.update( { _id: 1 }, { $set: { "contribs.1": "ALGOL 58" } } ) • Update an Element if Position is Unknown If the position in the array is not known, the update() method can perform the update using the $ positional operator. The array field must appear in the <query> parameter in order to determine which array element to update. The following operation queries the bios collection for the first document where the _id field equals 3 and the contribs array contains an element equal to compiler. If found, the update() method updates the first matching element in the array to A compiler in the document: db.bios.update( { _id: 3, "contribs": "compiler" }, { $set: { "contribs.$": "A compiler" } } )
  • 24. Update Arrays • Update a Document Element The update() method can perform the update of an array that contains subdocuments by using the positional operator (i.e. $) and the dot notation. The following operation queries the bios collection for the first document where the _id field equals 6 and the awards array contains a subdocument element with the by field equal to ACM. If found, the update() method updates the by field in the first matching subdocument: db.bios.update( { _id: 6, "awards.by": "ACM" } , { $set: { "awards.$.by": "Association for Computing Machinery" } } ) • Add an Element The following operation queries the bios collection for the first document that has an _id field equal to 1 and adds a new element to the awards field: db.bios.update( { _id: 1 }, { $push: { awards: { award: "IBM Fellow", year: 1963, by: "IBM" } } } )
  • 25. Mongo Shell Methods JavaScript in MongoDB Although these methods use JavaScript, most interactions with MongoDB do not use JavaScript but use an idiomatic driver in the language of the interacting application. Collection Functions Name Description db.collection.aggregate() Provides access to the aggregation pipeline. db.collection.distinct() Returns an array of documents that have distinct values for the specified field. db.collection.drop() Removes the specified collection from the database. db.collection.dropIndex() Removes a specified index on a collection. db.collection.dropIndexes() Removes all indexes on a collection. db.collection.ensureIndex() Creates an index if it does not currently exist. If the index existsensureIndex() does nothing. db.collection.find() Performs a query on a collection and returns a cursor object. db.collection.findAndModify() Atomically modifies and returns a single document. db.collection.findOne() Performs a query and returns a single document. db.collection.getIndexes() Returns an array of documents that describe the existing indexes on a collection. db.collection.group() Provides simple data aggregation function. Groups documents in a collection by a key, and processes the results. Use aggregate() for more complex data aggregation. db.collection.insert() Creates a new document in a collection. db.collection.mapReduce() erforms map-reduce style data aggregation. db.collection.reIndex() Rebuilds all existing indexes on a collection. db.collection.remove() Deletes documents from a collection. db.collection.renameCollection() Changes the name of a collection. db.collection.save() Provides a wrapper around an insert() and update() to insert new documents. db.collection.update() Modifies a document in a collection.
  • 26. Mongo Shell Methods Cursor Functions Name Description cursor.count() Returns a count of the documents in a cursor. cursor.explain() Reports on the query execution plan, including index use, for a cursor. cursor.hint() Forces MongoDB to use a specific index for a query. cursor.limit() Constrains the size of a cursor’s result set. cursor.map() Applies a function to each document in a cursor and collects the return values in an array. cursor.max() Specifies an exclusive upper index bound for a cursor. For use with cursor.hint() cursor.min() Specifies an inclusive lower index bound for a cursor. For use with cursor.hint() cursor.next() Returns the next document in a cursor. cursor.size() Returns a count of the documents in the cursor after applying skip() and limit()methods. cursor.skip() Returns a cursor that begins returning results only after passing or skipping a number of documents. cursor.sort() Returns results ordered according to a sort specification. cursor.toArray() Returns an array that contains all documents returned by the cursor. More shell functions @ http://docs.mongodb.org/manual/reference/method/