Search for notes by fellow students, in your own course and all over the country.
Browse our notes for titles which look like what you need, you can preview any of the notes via a sample of the contents. After you're happy these are the notes you're after simply pop them into your shopping cart.
Title: Mongo db
Description: These are handwritten notes of mongo db which are helpful in programming which are in a very simple language and easy to understand
Description: These are handwritten notes of mongo db which are helpful in programming which are in a very simple language and easy to understand
Document Preview
Extracts from the notes are below, to see the PDF you'll receive please use the links above
Chapter 1
About This Book
1
License
The Little MongoDB Book book is licensed under the Attribution-NonCommercial 3
...
You should not
have paid for this book
...
However, I ask that you always attribute the
book to me, Karl Seguin and do not use it for commercial purposes
...
org/licenses/by-nc/3
...
He’s an expert
...
He’s a semi-active contributor to OSS projects, a technical writer and an occasional speaker
...
His free service for casual game developers, mogade
...
Karl has since written The Little Redis Book
His blog can be found at http://openmymind
...
com/karlseguin)
3
With Thanks To
A special thanks to Perry Neal for lending me his eyes, mind and passion
...
Thank
you
...
6 by Asya Kamsky
...
com/karlseguin/the-little-mongodb-book
...
It is often said that technology moves at a blazing pace
...
However, I’ve long been of the opinion that the fundamental technologies used by
programmers move at a rather slow pace
...
What is striking
though is the speed at which established technologies get replaced
...
Nothing could be more representative of this sudden shift than the progress of NoSQL technologies against wellestablished relational databases
...
Even though these transitions seem to happen overnight, the reality is that they can take years to become accepted
practice
...
Solutions are refined,
lessons learned and seeing that a new technology is here to stay, others slowly try it for themselves
...
Having said all of that, the first thing we ought to do is explain what is meant by NoSQL
...
Personally, I use it very broadly to mean a system that plays a part in the
storage of data
...
Where relational database vendors have historically tried to position their software
as a one-size-fits-all solution, NoSQL leans towards smaller units of responsibility where the best tool for a given job
can be leveraged
...
Put
simply, NoSQL is about being open and aware of alternative, existing and additional patterns and tools for managing
your data
...
As a document-oriented database, MongoDB is a more
generalized NoSQL solution
...
Like relational databases, it
too can benefit from being paired with some of the more specialized NoSQL solutions
...
8
Chapter 3
Getting Started
Most of this book will focus on core MongoDB functionality
...
While the shell
is useful to learn as well as being a useful administrative tool, your code will use a MongoDB driver
...
MongoDB has a number of official drivers
for various languages
...
On top of these drivers, the development community has built more language/framework-specific libraries
...
Whether you choose to program directly against the core MongoDB drivers or some higher-level library is
up to you
...
As you read through this, I encourage you to play with MongoDB to replicate what I demonstrate as well as to explore
questions that you might come up with on your own
...
1
...
For development purposes, you can pick either 32-bit or 64-bit
...
Extract the archive (wherever you want) and navigate to the bin subfolder
...
3
...
config
...
Add a single line to your mongodb
...
For example, on Windows you might do dbpath=c:\mongodb\data and on Linux you might do dbpath=/var/
lib/mongodb/data
...
Make sure the dbpath you specified exists
...
Launch mongod with the --config /path/to/your/mongodb
...
9
As an example for Windows users, if you extracted the downloaded file to c:\mongodb\ and you created c:\mongodb\
data\ then within c:\mongodb\bin\mongodb
...
You could then
launch mongod from a command prompt via c:\mongodb\bin\mongod --config c:\mongodb\bin\mongodb
...
Feel free to add the bin folder to your path to make all of this less verbose
...
The only thing you should have to change are the paths
...
If you get an error, read the output carefully - the server is quite
good at explaining what’s wrong
...
Try entering db
...
Hopefully you’ll see the version number you installed
...
Obviously this is core to
understanding MongoDB, but it should also help us answer higher-level questions about where MongoDB fits
...
1
...
Within a MongoDB instance you can have zero or more databases, each acting as high-level
containers for everything else
...
A database can have zero or more collections
...
3
...
Again, a document can safely be thought of as a row
...
A document is made up of one or more fields, which you can probably guess are a lot like columns
...
Indexes in MongoDB function mostly like their RDBMS counterparts
...
Cursors are different than the other five concepts but they are important enough, and often overlooked, that
I think they are worthy of their own discussion
...
To recap, MongoDB is made up of databases which contain collections
...
Each document is made up of fields
...
Finally, when we get data from MongoDB we do so through a cursor whose actual execution is delayed until necessary
...
table, document vs
...
column)? Is it just to make things more
complicated? The truth is that while these concepts are similar to their relational database counterparts, they are not
identical
...
That is to say that each document within a
collection can have its own unique set of fields
...
11
Although this is important to understand, don’t worry if things aren’t yet clear
...
Ultimately, the point is that a collection isn’t strict about what goes in it (it’s
schema-less)
...
The benefits and drawbacks of this will be explored
in a future chapter
...
If you don’t have it running already, go ahead and start the mongod server as well as a mongo
shell
...
There are some global commands you can execute, like help or exit
...
help() or db
...
Commands that you execute against a specific collection, which is what we’ll be doing a lot of, are executed against
the db
...
unicorns
...
unicorns
...
Go ahead and enter db
...
A small side note: Because this is a JavaScript shell, if you execute a method and omit the parentheses (), you’ll
see the method body rather than executing the method
...
){ you won’t be surprised
...
help (without the
parentheses), you’ll see the internal implementation of the help method
...
It doesn’t matter that the
database doesn’t really exist yet
...
Now
that you are inside a database, you can start issuing database commands, like db
...
If you do
so, you should get an empty array ([ ])
...
We can simply insert a document into a new collection
...
unicorns
...
Internally MongoDB
uses a binary serialized JSON format called BSON
...
If we execute db
...
You can now use the find command against unicorns to return a list of documents:
db
...
find()
Notice that, in addition to the data you specified, there’s an _id field
...
You can either generate one yourself or let MongoDB generate a value for you which has the type ObjectId
...
By default, the _id field is indexed
...
unicorns
...
Now, back to our discussion about schema-less collections
...
unicorns
...
Once we know a bit more, we’ll discuss this interesting behavior of MongoDB,
but hopefully you are starting to understand why the more traditional terminology wasn’t a good fit
...
A MongoDB query selector is like the where clause of an
SQL statement
...
A
selector is a JSON object, the simplest of which is {} which matches all documents
...
Before delving too deeply into selectors, let’s set up some data to play with
...
unicorns
...
Now, issue the following inserts to get some data we can play
with (I suggest you copy and paste this):
db
...
insert({name: 'Horny',
dob: new Date(1992,2,13,7,47),
loves: ['carrot','papaya'],
weight: 600,
gender: 'm',
vampires: 63});
db
...
insert({name: 'Aurora',
dob: new Date(1991, 0, 24, 13, 0),
loves: ['carrot', 'grape'],
weight: 450,
gender: 'f',
vampires: 43});
db
...
insert({name: 'Unicrom',
dob: new Date(1973, 1, 9, 22, 10),
loves: ['energon', 'redbull'],
weight: 984,
gender: 'm',
vampires: 182});
db
...
insert({name: 'Roooooodles',
dob: new Date(1979, 7, 18, 18, 44),
loves: ['apple'],
weight: 575,
gender: 'm',
vampires: 99});
db
...
insert({name: 'Solnara',
dob: new Date(1985, 6, 4, 2, 1),
loves:['apple', 'carrot',
'chocolate'],
weight:550,
gender:'f',
vampires:80});
db
...
insert({name:'Ayna',
14
dob: new Date(1998, 2, 7, 8, 30),
loves: ['strawberry', 'lemon'],
weight: 733,
gender: 'f',
vampires: 40});
db
...
insert({name:'Kenny',
dob: new Date(1997, 6, 1, 10, 42),
loves: ['grape', 'lemon'],
weight: 690,
gender: 'm',
vampires: 39});
db
...
insert({name: 'Raleigh',
dob: new Date(2005, 4, 3, 0, 57),
loves: ['apple', 'sugar'],
weight: 421,
gender: 'm',
vampires: 2});
db
...
insert({name: 'Leia',
dob: new Date(2001, 9, 8, 14, 53),
loves: ['apple', 'watermelon'],
weight: 601,
gender: 'f',
vampires: 33});
db
...
insert({name: 'Pilot',
dob: new Date(1997, 2, 1, 5, 3),
loves: ['apple', 'watermelon'],
weight: 650,
gender: 'm',
vampires: 54});
db
...
insert({name: 'Nimue',
dob: new Date(1999, 11, 20, 16, 15),
loves: ['grape', 'carrot'],
weight: 540,
gender: 'f'});
db
...
insert({name: 'Dunx',
dob: new Date(1976, 6, 18, 18, 18),
loves: ['grape', 'watermelon'],
weight: 704,
gender: 'm',
vampires: 165});
Now that we have data, we can master selectors
...
{field1: value1, field2: value2} is how we do an and statement
...
For
example, to get all male unicorns that weigh more than 700 pounds, we could do:
db
...
find({gender: 'm',
weight: {$gt: 700}})
//or (not quite the same thing, but for
//demonstration purposes)
db
...
find({gender: {$ne: 'f'},
weight: {$gte: 701}})
The $exists operator is used for matching the presence or absence of a field, for example:
db
...
find({
vampires: {$exists: false }})
should return a single document
...
unicorns
...
If we want to OR rather than AND several conditions on different fields, we use the $or operator and assign to it an
array of selectors we want or’d:
db
...
find({gender: 'f',
$or: [{loves: 'apple'},
{weight: {$lt: 500}}]})
The above will return all female unicorns which either love apples or weigh less than 500 pounds
...
You might have already noticed, but the loves field
is an array
...
This is an incredibly handy feature
...
What’s more interesting is how easy selecting based on an array value
is: {loves: 'watermelon'} will return any document where watermelon is a value of loves
...
These are all described in the Query Selectors section
of the MongoDB manual
...
It’s also what you’ll
end up using most of the time
...
They can also be used with the remove command
which we’ve briefly looked at, the count command, which we haven’t looked at but you can probably figure out, and
the update command which we’ll spend more time with later on
...
unicorns
...
However, we did
get MongoDB up and running, looked briefly at the insert and remove commands (there isn’t much more than what
we’ve seen)
...
We’ve had a good start and
laid a solid foundation for things to come
...
I strongly urge you to play with your
local copy before moving on
...
Use find, count and remove
...
17
18
Chapter 5
Chapter 2 - Updating
In chapter 1 we introduced three of the four CRUD (create, read, update and delete) operations
...
Update has a few surprising behaviors, which is why we dedicate a
chapter to it
...
If
Roooooodles had gained a bit of weight, you might expect that we should execute:
db
...
update({name: 'Roooooodles'},
{weight: 590})
(If you’ve played with your unicorns collection and it doesn’t have the original data anymore, go ahead and remove
all documents and re-insert from the code in chapter 1
...
unicorns
...
No document is found because the second parameter we supplied
didn’t have any update operators, and therefore it was used to replace the original document
...
There is no equivalent functionality to this in SQL’s update command
...
However, when you want to change the value of one, or a few fields, you
must use MongoDB’s $set operator
...
unicorns
...
Now if we execute:
db
...
find({name: 'Roooooodles'})
We get the expected result
...
unicorns
...
All update operators work on fields - so
your entire document won’t be wiped out
...
If Pilot was incorrectly awarded a couple vampire kills, we could correct the mistake by
executing:
db
...
update({name: 'Pilot'},
{$inc: {vampires: -2}})
If Aurora suddenly developed a sweet tooth, we could add a value to her loves field via the $push operator:
db
...
update({name: 'Aurora'},
{$push: {loves: 'sugar'}})
The Update Operators section of the MongoDB manual has more information on the other available update operators
...
An upsert updates the document
if found or inserts it if not
...
To enable upserting we pass a third parameter to update {upsert:true}
...
If we wanted to keep an aggregate count in real time, we’d have
to see if the record already existed for the page, and based on that decide to run an update or insert
...
hits
...
hits
...
hits
...
hits
...
If we execute it a second
time, the existing document is updated and hits is incremented to 2
...
hits
...
hits
...
So far, for the examples we’ve
looked at, this might seem logical
...
unicorns
...
unicorns
...
To get the behavior you desire, the multi
option must be set to true:
db
...
update({},
{$set: {vaccinated: true }},
{multi: true });
db
...
find({vaccinated: true });
23
In This Chapter
This chapter concluded our introduction to the basic CRUD operations available against a collection
...
First, if you pass it a document without update operators,
MongoDB’s update will replace the existing document
...
Secondly, update supports an intuitive upsert
option which is particularly useful when you don’t know if the document already exists
...
24
Chapter 6
Chapter 3 - Mastering Find
Chapter 1 provided a superficial look at the find command
...
We already mentioned that the result from find is a cursor
...
25
Field Selection
Before we jump into cursors, you should know that find takes a second optional parameter called “projection”
...
For example, we can get all of the unicorns’ names without
getting back other fields by executing:
db
...
find({}, {name: 1});
By default, the _id field is always returned
...
Aside from the _id field, you cannot mix and match inclusion and exclusion
...
You either want to select or exclude one or more fields explicitly
...
However, what
you’ve no doubt observed from the shell is that find executes immediately
...
We can
observe the true behavior of cursors by looking at one of the methods we can chain to find
...
We specify the fields we want to sort on as a JSON document, using 1 for ascending and -1 for descending
...
unicorns
...
sort({weight: -1})
//by unicorn name then vampire kills:
db
...
find()
...
We’ll look at indexes in more detail later on
...
That is, if you try to sort a very
large result set which can’t use an index, you’ll get an error
...
In truth, I wish
more databases had the capability to refuse to run unoptimized queries
...
)
27
Paging
Paging results can be accomplished via the limit and skip cursor methods
...
unicorns
...
sort({weight: -1})
...
skip(1)
Using limit in conjunction with sort, can be a way to avoid running into problems when sorting on non-indexed fields
...
unicorns
...
Drivers which don’t provide such a
shortcut need to be executed like this (which will also work in the shell):
db
...
find({vampires: {$gt: 50}})
...
There are a few additional commands that we’ll either cover
in later chapters or which only serve edge cases, but, by now, you should be getting pretty comfortable working in the
mongo shell and understanding the fundamentals of MongoDB
...
Explaining a few new terms and some new
syntax is a trivial task
...
The truth is that
most of us are still finding out what works and what doesn’t when it comes to modeling with these new technologies
...
Out of all NoSQL databases, document-oriented databases are probably the most similar to relational databases - at
least when it comes to modeling
...
31
No Joins
The first and most fundamental difference that you’ll need to get comfortable with is MongoDB’s lack of joins
...
That is, once you start to split your data horizontally, you end up performing your joins
on the client (the application server) anyway
...
Without knowing anything else, to live in a join-less world, we have to do joins ourselves within our application’s code
...
Setting our data up isn’t
any different than declaring a foreign key in a relational database
...
The first thing we’ll do is create an employee (I’m providing an explicit _id so
that we can build coherent examples)
db
...
insert({_id: ObjectId(
"4d85c7039ab0fd70a117d730"),
name: 'Leto'})
Now let’s add a couple employees and set their manager as Leto:
db
...
insert({_id: ObjectId(
"4d85c7039ab0fd70a117d731"),
name: 'Duncan',
manager: ObjectId(
"4d85c7039ab0fd70a117d730")});
db
...
insert({_id: ObjectId(
"4d85c7039ab0fd70a117d732"),
name: 'Moneo',
manager: ObjectId(
"4d85c7039ab0fd70a117d730")});
(It’s worth repeating that the _id can be any unique value
...
)
Of course, to find all of Leto’s employees, one simply executes:
db
...
find({manager: ObjectId(
"4d85c7039ab0fd70a117d730")})
There’s nothing magical here
...
32
Arrays and Embedded Documents
Just because MongoDB doesn’t have joins doesn’t mean it doesn’t have a few tricks up its sleeve
...
As a simple example, if an employee could have two
managers, we could simply store these in an array:
db
...
insert({_id: ObjectId(
"4d85c7039ab0fd70a117d733"),
name: 'Siona',
manager: [ObjectId(
"4d85c7039ab0fd70a117d730"),
ObjectId(
"4d85c7039ab0fd70a117d732")] })
Of particular interest is that, for some documents, manager can be a scalar value, while for others it can be an array
...
employees
...
Besides arrays, MongoDB also supports embedded documents
...
employees
...
employees
...
mother': 'Chani'})
We’ll briefly talk about where embedded documents fit and how you should use them
...
employees
...
Historically, denormalization was reserved for
performance-sensitive code, or when data should be snapshotted (like in an audit log)
...
This doesn’t mean you should duplicate every piece of information in every document
...
For example, say you are writing a forum application
...
With such a model, you can’t display posts without retrieving (joining to) users
...
You could even do so with an
embedded document, like user: {id: ObjectId('Something'), name: 'Leto'}
...
Adjusting to this kind of approach won’t come easy to some
...
Don’t be afraid to experiment with this approach though
...
35
Which Should You Choose?
Arrays of ids can be a useful strategy when dealing with one-to-many or many-to-many scenarios
...
First, you should know that an individual document is currently limited to 16 megabytes in size
...
At this point, it
seems like most developers lean heavily on manual references for most of their relationships
...
A real world example may be to store an addresses documents with each user, something like:
db
...
insert({name: 'leto',
email: 'leto@dune
...
43rd St",
city: "New York", state:"NY",zip:"10036"},
{street: "555 University",
city: "Palo Alto", state:"CA",zip:"94107"}]})
This doesn’t mean you should underestimate the power of embedded documents or write them off as something of
minor utility
...
This is especially true when you consider that MongoDB lets you query and index fields of an embedded
documents and arrays
...
Most MongoDB systems are laid out somewhat similarly to
what you’d find in a relational system, though with fewer collections
...
The conversation gets even more interesting when you consider embedded documents
...
Should you have a posts collection and a comments collection, or should each post have an array
of comments embedded within it? Setting aside the 16MB document size limit for the time being (all of Hamlet is less
than 200KB, so just how popular is your blog?), most developers should prefer to separate things out
...
MongoDB’s flexible schema allows you to combine the two
approaches by keeping comments in their own collection but embedding a few comments (maybe the first few) in the
blog post to be able to display them with the post
...
There’s no hard rule (well, aside from 16MB)
...
37
In This Chapter
Our goal in this chapter was to provide some helpful guidelines for modeling your data in MongoDB, a starting point,
if you will
...
You
have more flexibility and one constraint, but for a new system, things tend to fit quite nicely
...
38
Chapter 8
Chapter 5 - When To Use MongoDB
By now you should have a feel for where and how MongoDB might fit into your existing system
...
For me, the most important lesson, which has nothing to do with MongoDB, is that you no longer have to rely on a
single solution for dealing with your data
...
The idea isn’t that you must use different technologies,
but rather that you can
...
With that said, I’m hopeful that what you’ve seen so far has made you see MongoDB as a general solution
...
Therefore, rather than tiptoeing around it, let’s simply state that MongoDB should be seen as a direct alternative to
relational databases
...
Notice that I didn’t call MongoDB a replacement for relational databases, but rather an alternative
...
Some of it MongoDB does better, some of it MongoDB does worse
...
39
Flexible Schema
An oft-touted benefit of document-oriented database is that they don’t enforce a fixed schema
...
I agree that flexible schema is a nice feature, but not for the main
reason most people mention
...
There are domains and
data sets which can really be a pain to model using relational databases, but I see those as edge cases
...
It’s true that having an occasional mismatch can be handy,
especially when you introduce new features, but in reality it’s nothing a nullable column probably wouldn’t solve just
as well
...
This is particularly
true when you’re working with a static language
...
Ruby’s dynamism and its popular ActiveRecord implementations already reduce much of the object-relational
impedance mismatch
...
Rather, I think most
Ruby developers would see MongoDB as an incremental improvement, whereas C# or Java developers would see a
fundamental shift in how they interact with their data
...
You want to save an object? Serialize it to JSON (technically
BSON, but close enough) and send it to MongoDB
...
This straightforwardness definitely flows to you, the end developer
...
There are two aspects of MongoDB which make writes
quite fast
...
Secondly, you can control the write behavior with respect to data durability
...
In addition to these performance factors, log data is one of those data sets which can often take advantage of schemaless collections
...
So far, all of the implicitly created collections we’ve created are just normal collections
...
createCollection
command and flagging it as capped:
//limit our capped collection to 1 megabyte
db
...
A limit on the number
of documents, rather than the size, can be set using max
...
For
example, you can update a document but it can’t change in size
...
You can “tail” a capped collection the way you tail a file in Unix
via tail -f
...
41
Durability
Prior to version 1
...
That is, a server crash would likely result in lost or
corrupt data
...
Journaling was one of the major features added in 1
...
Since version 2
...
Durability is only mentioned here because a lot has been made around MongoDB’s past lack of single-server durability
...
Information you find about journaling being a missing
feature is simply out of date
...
It supports fifteen languages with stemming and stop
words
...
43
Transactions
MongoDB doesn’t have transactions
...
The first is its many atomic update operations
...
We
already saw some of the simpler ones, like $inc and $set
...
The second, when atomic operations aren’t enough, is to fall back to a two-phase commit
...
It’s a storage-agnostic solution that you do in code
...
The MongoDB website has an example illustrating the most typical example (a transfer of funds)
...
MongoDB’s support for nested documents and flexible schema design makes two-phase commits slightly less painful,
but it still isn’t a great process, especially when you are just getting started with it
...
2 MongoDB relied on MapReduce for most data processing jobs
...
2 it has added a powerful
feature called aggregation framework or pipeline, so you’ll only need to use MapReduce in rare cases where you
need complex functions for aggregations that are not yet supported in the pipeline
...
For now you can think of them as feature-rich and different ways to
group by (which is an understatement)
...
Thankfully, since the two systems really do complement each other, there’s a MongoDB connector
for Hadoop
...
There are plans for future
versions of MongoDB to be better at handling very large sets of data
...
This allows you to store either geoJSON
or x and y coordinates within documents and then find documents that are $near a set of coordinates or $within a box
or circle
...
46
Tools and Maturity
You probably already know the answer to this, but MongoDB is obviously younger than most relational database
systems
...
Nevertheless, an honest assessment simply can’t ignore the fact that MongoDB
is younger and the available tooling around isn’t great (although the tooling around a lot of very mature relational
databases is pretty horrible too!)
...
On the positive side, drivers exist for a great many languages, the protocol is modern and simple, and development
is happening at blinding speeds
...
47
In This Chapter
The message from this chapter is that MongoDB, in most cases, can replace a relational database
...
The lack of transactions
can be a legitimate and serious concern
...
48
Chapter 9
Chapter 6 - Aggregating Data
49
Aggregation Pipeline
Aggregation pipeline gives you a way to transform and combine documents in your collection
...
The simplest aggregation you are probably already familiar with is the SQL group by expression
...
unicorns
...
For a simple count grouped
by something, we only need one such operator and it’s called $group
...
You probably noticed that the _id field was assigned '$gender' and not 'gender' - the '$' before
a field name indicates that the value of this field from incoming document will be substituted
...
db
...
aggregate([{$match: {weight:{$lt:600}}},
{$group: {_id:'$gender',
total:{$sum:1},
avgVamp:{$avg:'$vampires'}}},
{$sort:{avgVamp:-1}} ])
Here we introduced another pipeline operator $sort which does exactly what you would expect, along with it we also
get $skip and $limit
...
MongoDB arrays are powerful and they don’t stop us from being able to aggregate on values that are stored inside of
them
...
unicorns
...
$sort and $limit in combination allow you to get answers to “top N” types of questions
...
For
example, you can use math operators to add together values of several fields before finding out the average, or you
can use string operators to create a new field that’s a concatenation of some existing fields
...
In 2
...
You can see a lot more
examples as well as all of the supported pipeline and expression operators in the MongoDB manual
...
First you map, and then you reduce
...
Then,
key/value pairs are grouped by key, such that values for the same key end up in an array
...
The map and reduce functions are written in
JavaScript
...
mapReduce takes a map function, a reduce function
and an output directive
...
From most libraries you supply a
string of your functions (which is a bit ugly)
...
We can also supply a finalize method to be applied to the
results after the reduce step
...
52
In This Chapter
In this chapter we covered MongoDB’s aggregation capabilities
...
MapReduce is more complicated to
understand, but its capabilities can be as boundless as any code you can write in JavaScript
...
We won’t dive deeply into either topic, but we will examine the most important aspects of each
...
Indexes in MongoDB work a lot like indexes in a relational database: they help improve query and sorting performance
...
unicorns
...
unicorns
...
unicorns
...
We can also create
compound indexes:
db
...
ensureIndex({name: 1,
vampires: -1});
The direction of your index (1 for ascending, -1 for descending) doesn’t matter for a single key index, but it can make
a difference for compound indexes when you are sorting on more than one indexed field
...
56
Explain
To see whether or not your queries are using an index, you can use the explain method on a cursor:
db
...
find()
...
If we change our query to use an index, we’ll see that a BtreeCursor was used, as well as the index used to fulfill the
request:
db
...
find({name: 'Pilot'})
...
All production deployments should be replica sets, which consist of ideally three or more servers that hold the same data
...
You can control whether
you allow reads to happen on secondaries or not, which can help direct some special queries away from the primary,
at the risk of reading slightly stale data
...
Again, MongoDB replication is outside the scope of this book
...
Sharding is an approach to scalability which partitions your data across multiple
servers or clusters
...
Thankfully, MongoDB’s sharding capabilities far exceed such a simple algorithm
...
While replication can help performance somewhat (by isolating long running queries to secondaries, and reducing
latency for some other types of queries), its main purpose is to provide high availability
...
Combining replication with sharding is the perscribed approach to achieve
scaling and high availability
...
stats()
...
You can also get statistics on a collection, say unicorns, by typing db
...
stats()
...
60
Profiler
You enable the MongoDB profiler by executing:
db
...
unicorns
...
system
...
find()
The output tells us what was run and when, how many documents were scanned, and how much data was returned
...
Specifying 1 as the first
parameter will profile queries that take more than 100 milliseconds
...
setProfilingLevel(1, 1000);
61
Backups and Restore
Within the MongoDB bin folder is a mongodump executable
...
You can type mongodump --help to see additional options
...
You can then use the mongorestore executable, located in the same bin folder, to restore a previously
made backup
...
mongodump and mongorestore operate on BSON, which is MongoDB’s native format
...
bson
It’s worth pointing out that mongoexport and mongoimport are two other executables which can be used to export and
import data from JSON or CSV
...
Only mongodump and mongorestore
should ever be used for actual backups
...
62
In This Chapter
In this chapter we looked at various commands, tools and performance details of using MongoDB
...
Indexing in MongoDB is similar to indexing with relational
databases, as are many of the tools
...
63
64
Chapter 11
Conclusion
You should have enough information to start using MongoDB in a real project
...
The MongoDB website has a lot of useful information
...
NoSQL was born not only out of necessity, but also out of an interest in trying new approaches
...
This, I think, is a
good way to lead our professional lives
Title: Mongo db
Description: These are handwritten notes of mongo db which are helpful in programming which are in a very simple language and easy to understand
Description: These are handwritten notes of mongo db which are helpful in programming which are in a very simple language and easy to understand