Total Visitors

Sunday, January 21, 2018

MongoDB : Basic Information

This is a small tutorial to learn the basics of MongoDB. The market for nosql is booming a lot! 
Its always good to have a basic idea about various nosql databases.

Installation with macOS:


  1. Try to install mongoDB through brew (software package management system that simplifies the installation of software on Apple MacOS)
  2. Go to https://brew.sh/ , copy paste the Terminal prompt command and run it on the mac terminal.
  3. Run command: "brew install mongodb" on your terminal.
  4. Make the data directory "mkdir -p /data/db"
  5. Change the Owner "sudo chown nelson /data/db"
  6. To see the databases created, type the command "show dbs"
  7. In order to create a new db and/or to switch to another db, type in the terminal "use test_1" (here while typing this for the first time, the 'test_1' db is created as well as it will switch the db to 'test_1')
Now these are few basic operations:

1.     Show the document with db.test_1.find()
2.     Update the database to allow a list of references
          nelsonDB.references = [ ]
              db.test_1.update({"name" : "Nelson"}, nelsonDB)
              db.test_1.find() // Will show the updated document

3.     Show the document with db.test_1.find()

4.     Update the database to allow a list of references

nelsonDB.references = [ ]
db.test_1.update({"name" : "Nelson"}, nelsonDB)

db.test_1.find() // Will show the updated document

5.     Use remove to delete the documents or with a parameter to delete just the one that matches

db.test_1.remove({"name" : "Nelson"})

db.test_1.find() // Will not show any result

6.     Data Types

a. null : {"name" : null}
b. boolean : {"currentEmp" : true}
c. number : (64 bit float) : {"height" : 6.25}
                  1. 4 byte Int : {"bigint" : 92949455}
                  2. 8 byte Long : {"bigLong" : 78443435227370955145644}
d. string : {"address" : "N Avenue"}
e. Array containing multiple datatypes : array : {"grades" : ["a", "b", "c", "d"]}
f.  Date object : {"hiredate" : new Date()}
g. Regular expression : {"addressregex" : /^[A-Za-z0-9\.\' \-]{4,33}$/}
h. Embedded document : {"info" : {"name" : "Baker Smith"}}
i. Object id (Unique for every document) : 12 Byte ID for documents

j. Randomdata = {"name" : null, "over20" : true, "height" : 6.25,
"bigint" : 92949455, "bigLong" : 78443435227370955145644,
"address" : "N Avenue", "grades" : ["a", "b", "c", "d"],
"hiredate" : new Date(), "streetregex" : '/^[A-Za-z0-9\.\' \-]{5,30}$/',
"info" : {"name" : "Baker Smith"}}

More about MongoDB


Create a User with Roles:

db.createUser ({
                  user: "Nelson",
                  pwd: "1234"
                  roles: ["readWrite”""dbAdmin"]

});

Create a User without Roles:

db.createUser ({
                  user: "Nelson",
                  pwd: "1234",
                  roles: []

});

Note*: If you type pass instead of pwd, it will throw the following error:
Error: couldn't add user: "pass" is not a valid argument to createUser 

Collections are very similar to tables in database:

Create a collection:
db.createCollection('customers');
show collections

And insert few values:
db.customers.insert({"firstName":"John", "lastName":"Baker"})

db.customers.find()

If we need to add multiple row, use array
db.customers.insert([{"firstName":"Sarah", "lastName":"Anderson"},{"firstName":"Steve", "lastName":"Joseph",gender:"Male"}])

Output:
db.customers.find().pretty()

{
"_id" : ObjectId("5a668d7608220527b462d543"),
"firstName" : "John",
"lastName" : "Baker"
}
{
"_id" : ObjectId("5a668ebc08220527b462d544"),
"firstName" : "Sarah",
"lastName" : "Anderson"
}
{
"_id" : ObjectId("5a668ebc08220527b462d545"),
"firstName" : "Steve",
"lastName" : "Joseph",
 "gender" : "Male"

}


Note*: Here we can see that we can add one more field called "gender" into the document.


Now to update it always try to use the objectId instead of any first_name as reference. Just for understanding purpose I have taken first_name as a reference.

db.customers.update({"firstName":"Steve"}, {"firstName":"Steve", "lastName":"Joseph",gender:"Female"})


Note*: If we just use db.customers.insert({"firstName":"Steve"}, {gender:"Female"}) , it will replace the whole thing with just {gender:"Female"}

SET:

There is a way where this situation can be avoided, that is by using SET 

db.customers.update({"firstName":"Steve"}, {$set:{gender:"Female"}})

We can update a new field into it:

db.customers.update({"firstName":"Steve"}, {$set:{age:49}})

Increment age by 1:
db.customers.update({"firstName":"Steve"}, {$inc:{age:1}})


{
"_id" : ObjectId("5a668d7608220527b462d543"),
"firstName" : "John",
"lastName" : "Baker"
}
{
"_id" : ObjectId("5a668ebc08220527b462d544"),
"firstName" : "Sarah",
"lastName" : "Anderson"
}
{
"_id" : ObjectId("5a668ebc08220527b462d545"),
"firstName" : "Steve",
"lastName" : "Joseph",
"gender" : "Male",
"age":50
}

UNSET:
db.customers.update({"firstName":"Steve"}, {$unset:{age:1}})
Age will be deleted from the document.

UPSERT:
If the item is not found during the update then by using UPSERT it will add the items if matching items is not available.

db.customers.update({"firstName":"Job"}, {"firstName":"Job", "lastName":"Martin"},{upsert:true});

After executing this a new document will be added.

RENAME:
db.customers.update({"firstName":"Steve"}, {$rename:{gender:"sex"}})

output:
{
"_id" : ObjectId("5a668d7608220527b462d543"),
"firstName" : "John",
"lastName" : "Baker"
}
{
"_id" : ObjectId("5a668ebc08220527b462d544"),
"firstName" : "Sarah",
"lastName" : "Anderson"
}
{
"_id" : ObjectId("5a668ebc08220527b462d545"),
"firstName" : "Steve",
"lastName" : "Joseph",
"sex" : "Female"
}
{
"_id" : ObjectId("5a668f1108220527b462d547"),
"firstName" : "Steve",
"lastName" : "Joseph",
"gender" : "Male"
}
{ "_id" : ObjectId("5a66911708220527b462d548"), "firstName" : "Steve" }
{
"_id" : ObjectId("5a66b4b404b58ba782f4043a"),
"firstName" : "Job",
"lastName" : "Martin"

}

REMOVE:
To remove the document
db.customers.remove({"firstName":"Steve"});

Note*: If the above statement is executed, all the document related to firstName = 'Steve' will be deleted.
So use justOne
db.customers.remove({"firstName":"Steve"},{justOne:true});
This is a kind of safety option which only deletes the first document.

QUERYING the Document:

db.customers.find({firstName:"Sarah"})

OR db.customers.find({$or: [{"firstName":"Steve"},{"firstName":"John"}]});
Greater Than / Less Than


db.customers.find({"age": [{lt:60}]}); // replace lt with gt for finding greater than.

also,
lte - less than or equal to
gte - greater than or equal to

Insert Object
db.customers.update({"firstName":"TinTin"}, {"address":{"street":"S Avenue","city":"tempe","state":"AZ"}},{upsert:true});

find value from inside the object:
db.customers.find({"address.city":"tempe"})

Sort
Sorting the component by lastName.
db.customers.find().sort({lastName:1});

Note*: Here 1 means it is sorted in the ascending order, -1 means descending order.

Count
db.customers.find().count()
specific search:
db.customers.find({gender:"male"}).count()

Limit
db.customers.find({gender:"Male"}).limit(4)

db.customers.find().limit(4).sort({lastName:1})

ForEach
db.customers.find().forEach(function(doc){print("Customer Name: "+doc.firstName)})


output:
Customer Name: John
Customer Name: Steve
Customer Name: Sarah
Customer Name: Steve
Customer Name: Steve
Customer Name: Job



No comments:

Post a Comment