Monday, June 13, 2016

basic mongodb operation -- nosql database

1- install mongodb on ubuntu 16.04
$ sudo apt-get install mongodb-server mongodb-clients mongodb

- if the service does not start, start it with the following comment.
$ sudo /etc/init.d/mongodb start

2- to access mongodb shell we use mongo command,
$ mongo
MongoDB shell version: 2.6.10
connecting to: test


3- the structure is automatically, when we start using it.

- create databases, mydb we just use command use db (my you have to create a tables before the db stay exited)
> use mydb

- insert a record to the table, schoolrecord,  then the table will automatically create with the record insert
> db.schoolrecord.insert(
    {
       "firstname" : "gest",
       "lastname" : "derp1",
       "sex" : "male",
       "grades" : [
          {
             "date" : ISODate("2014-10-01T00:00:00Z"),
             "grade" : "A",
             "score" : 11
          }
     ]
 }
)

WriteResult({ "nInserted" : 1 })

-  list all databases
> show dbs
admin  (empty)
local  0.078GB
mydb   0.078GB
test   0.078GB


- list all tables
> show tables
restaurants
schoolrecord
system.indexes 





- query all records in table schoolrecord
> db.schoolrecord.find()
{ "_id" : ObjectId("575ec19bf0bc563047aaa1be"), "firstname" : "gest", "lastname" : "derp1", "sex" : "male", "grades" : [ { "date" : ISODate("2014-10-01T00:00:00Z"), "grade" : "A", "score" : 11 } ] }
{ "_id" : ObjectId("575ec26ff0bc563047aaa1bf"), "firstname" : "gest", "lastname" : "derp2", "sex" : "male", "grades" : [ { "date" : ISODate("2014-10-01T00:00:00Z"), "grade" : "C", "score" : 12 } ] }


- query only record with lastname=derp1, in table schoolrecord
> db.schoolrecord.find({"lastname":"derp1"})
{ "_id" : ObjectId("575ec19bf0bc563047aaa1be"), "firstname" : "gest", "lastname" : "derp1", "sex" : "male", "grades" : [ { "date" : ISODate("2014-10-01T00:00:00Z"), "grade" : "A", "score" : 11 } ] }


4- to exit mongodb shell use command quit()
> quit()

No comments:

Post a Comment