Monday, October 9, 2017

MongoDB fast-forward

Right into it

First of, here is how you create a new database in MongoDB:

use YOUR_DATABASE_NAME_HERE

You may be wondering why they called it "use". Well, because it's primarily intended for selecting database you wanna work with, but if such a database doesn't exist the command "use" creates it.

Now, if you wanna delete your database, you can do it this way:

db.dropDatabase()

But please, before you do, make sure you selected the right one using "use" command. If your uncertain which database you're working with, just enter "db" command  and it will show you the name of the currently selected database.

db

In case you're after different database, use "show dbs" command to see the list of all databases you possess:

show dbs

Keep in mind that newly created database won't get on that list until after you insert at least one document into it.

Documents

A document is basically MongoDB equivalent of SQL table. If you wanna create one, you can easily do it with "insert" command:

db.individuals.insert({
firstName: "John",
lastName: "Smith"
})


If you have been paying attention, you probably noticed that we used JSON to describe our document. Well, actually its a little bit more extended variety of JSON which MongoDB uses to store its documents as BSON (Binary JSON).

Now that you know how to create a document, naturally you might wanna know how to delete it. Let's start with deleting all available documents(we got just one, but imagine there are like tons of them):

db.individuals.remove()

Wait, what if we wanna remove only those whose last name is Smith? Well, thats why remove method accepts two optional arguments: deletion criteria and justOne flag. The signature looks somewhat like this:

db.individuals.remove(deletion_criteria, justOne)

Deletion criteria is simple JSON object describing what exactly you wanna remove, for example:

db.individuals.remove({lastName: "Smith"})

justOne flag, if passed, merely means that you wanna remove only the first document matching the criteria:

db.individuals.remove({lastName: "Smith"}, 1)

Collections

A collection is where you insert your documents into. Collections may be created either explicitly or implicitly. Until now we created them implicitly simply putting name of a collection in between db and insert:

db.YOUR_COLLECTION_NAME_HERE.insert()

If you wanna create a collection explicitly you need to call db.createCollection method, its signature looks like this:

db.createCollection(name, options)

Naturally, "name" is your collection name and "options" is where you put JSON object telling MongoDB what kind of a collection you want. Here you can get familiar with all the available collection options.

Ok, let's just explicitly create a collection without options:

db.createCollection("individuals")

Now, if you wanna make sure your collection exists, enter "show collections" command:

show collections

No comments:

Post a Comment