Mongodb: Excerpts From "The Little Mongodb Book" Karl Seguin
Mongodb: Excerpts From "The Little Mongodb Book" Karl Seguin
Mongodb: Excerpts From "The Little Mongodb Book" Karl Seguin
Excerpts from
“The Little MongoDB Book”
Karl Seguin
• Download MongoDB from https://www.mongodb.org
• Install (double-click!) and navigate to the bin subfolder (in MongoDB
3.2 it is at mongodb\Server\3.2\bin)
• Do not execute anything just yet, but know that mongod is the server
process and mongo is the client shell - these are the two executables
we will be spending most of our time with.
• Create a text file in the bin subfolder named mongodb.config
• Add a single line to your mongodb.config file:
dbpath=PATH_TO_WHERE_YOU_WANT_TO_STORE_YOUR_DATABASE
_FILES
• For example, on Windows you might do
dbpath=c:\mongodb\data
Make sure the dbpath you specified exists.
• Launch mongod (the server process): in Windows you could launch mongod
from mongodb\Server\3.2\bin\a command prompt via:
mongod --config c:\mongodb\Server\3.2\bin\mongodb.config
• You can also download a more friendly manager, for example, NoSQL Manager
http://www.mongodbmanager.com/mongodb/editions
• MongoDB has the same concept of a database with which you are
likely already familiar (a database schema).
• Within a MongoDB instance you can have zero or more databases.
• A database can have zero or more collections. A collection shares
enough in common with a traditional table
• Collections are made up of zero or more documents. 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.
• Notice that, in addition to the data you specified, there is an _id field.
Every document must have a unique _id field.
• You can either generate one yourself or let MongoDB generate a
value for you which has the type ObjectId. Most of the time you will
probably want to let MongoDB generate it for you.
• Now insert:
db.unicorns.insert({name: 'Leto',
gender: 'm',
home: 'Arrakeen',
worm: false})
db.unicorns.find()
• There is one practical aspect of MongoDB you need to have a good
grasp of before moving to more advanced topics: query selectors.
• First, remove what we have put so far in the unicorns collection via:
db.unicorns.remove({})
db.unicorns.find()
• Now that we have data, we can master selectors.
• {field: value} is used to find any documents where field is equal to
value.
• {field1: value1, field2: value2} is how we do an AND statement. The
special $lt, $lte, $gt, $gte and $ne are used for less than, less than or
equal, greater than, greater than or equal and not equal operations.
• For example, to get all male unicorns that weigh more than 700
pounds, we could do:
db.unicorns.find({gender: 'm', weight: {$gt: 700}})
or (not quite the same thing, but for demonstration purposes)
db.unicorns.find({gender: {$ne: 'f'}, weight: {$gte: 701}})
So this is an AND
• The $exists operator is used for matching the presence or absence of
a field, for example:
db.unicorns.find({vampires: {$exists: false}})
Field
• The $in operator is used for matching one of several values that we
pass as an array, for example:
db.unicorns.find({loves: {$in:['apple','orange']}})
• 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.unicorns.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.
• There is something pretty neat going on in our last two examples. You
might have already noticed, but the loves field is an array. MongoDB
supports arrays as first class objects. This is an incredibly handy
feature.
• Once you start using it, you wonder how you ever lived without it.
• What is 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.
• We have seen how these selectors can be used with the find
command. They can also be used with the remove command which
we have briefly looked at, the count command, which we have not
looked at but you can probably figure out, and the update command
which we will spend more time with later on.
• The ObjectId which MongoDB generated for our _id field can be
selected like so:
db.unicorns.find({_id: ObjectId("TheObjectId")})
Example:
db.unicorns.find({_id: ObjectId("56b3db6d323460b88657a52a")})
Updating
• We have introduced three of the four CRUD (create, read, update and
delete) operations. Now we focus on update.
• Update has a few surprising behaviors, let us see.
• In its simplest form, update takes two parameters: the selector to use
and what updates to apply to fields.
• Suppose that the unicorn “Roooooodles” had gained a bit of weight,
you might expect that we should execute:
db.unicorns.update({name: 'Roooooodles'}, {weight: 590})
db.unicorns.find({name: 'Pilot'})
• If Aurora suddenly developed a sweet tooth, we could add a value to
her loves field via the $push operator:
db.unicorns.update({name: 'Aurora'}, {$push: {loves: 'sugar'}})
db.unicorns.find({name: 'Aurora'})
• Paging: Paging results can be accomplished via the limit and skip
methods.
• To get the second and third heaviest unicorn, we could do:
db.unicorns.find().sort({weight: -1}).limit(2).skip(1)