Professional Documents
Culture Documents
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.com/download-
center/community
• Install (double-click) and follow the steps. This video may help:
https://www.youtube.com/watch?v=gkCnXcxHC4o
• Create data\db at root directory
• Navigate to the MongoDB bin subfolder (in MongoDB 4.2 it is at
Mongodb\Server\4.2\bin), mongod is the server process and mongo
is the client shell.
• Launch mongod (the server process, if it was not chosen as a service)
After launching it, do not close it!
• You can now launch mongo (without the d, in MongoDB 4.2 it is at Mongodb\
Server\4.2\bin) which will connect a shell to your running server. Just execute
mongo.exe from Windows
• You can also use a more friendly manager, for example, MongoDB Compass
or NoSQL Manager among others:
https://www.mongodbmanager.com/
• 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({})
Try also this: db.unicorns.drop()
Nota: remove y drop son análogos a delete y drop de SQL…
• Issue the inserts in the file unicorns.txt (ver menú Varios)
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")})
ObjectId: Methods and Attributes
• Returns the hexadecimal string representation of the object:
ObjectId("56b3db6d323460b88657a52a").str
• Returns the timestamp portion of the object as a Date:
ObjectId("56b3db6d323460b88657a52a").getTimestamp()
• Returns the JavaScript representation in the form of a string literal "ObjectId(...)":
ObjectId("56b3db6d323460b88657a52a").toString()
• Returns the representation of the object as a hexadecimal string.
The returned string is the str attribute:
• ObjectId("56b3db6d323460b88657a52a").valueOf()
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})
• You should discover the first surprise of update. No document is found! Because
the second parameter we supplied did not have any update operators (see next
slide $set operator), and therefore it was used to replace the original document.
In other words, the update found a document by name and replaced the entire
document with the new document (the second parameter)
db.unicorns.find({weight: 590})
Nifty = ingenioso
• If the unicorn “Pilot” was incorrectly awarded a couple vampire kills,
we could correct the mistake by executing:
db.unicorns.update({name: 'Pilot'}, {$inc: {vampires: -2}})
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}).skip(1).limit(2)