First steps in MongoDB

Step1. Installation.

The mongodb-org package does not exist within the default repositories for CentOS. However, MongoDB maintains a dedicated repository. Let’s add it to our server.

sudo vi /etc/yum.repos.d/mongodb-org.repo

/etc/yum.repos.d/mongodb-org.repo

[mongodb-org-3.2]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/3.2/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-3.2.asc
yum repolist

sudo yum install mongodb-org 
sudo systemctl reload mongod
sudo systemctl enable mongod

Step2. Basic managing commands.

db.dropDatabase()
Login to mongo shell [root@mongodb ~]# mongo
Create database > use mydb
switched to db mydb
Drop database db.dropDatabase()
Show existed databases show dbs
Create collection db.createCollection(name, options)
>db.createCollection(“mycollection”)
{ “ok” : 1 }
Show collections > show collections
mainCol
movie
newCol

In MongoDB, you don’t need to create collection. MongoDB creates collection automatically, when you insert some document.

>db.newCollection.insert({“name” : “some data”})

> show collections
mainCol
movie
newCol
newCollection

 

Drop collection db.COLLECTION_NAME.drop()

 

Step 3. Basic data management

Insert the document

>db.COLLECTION_NAME.insert(document)

Example:

>db.post.insert([
   {
      title: ‘MongoDB Overview’,
      description: ‘MongoDB is no sql database’,
      by: ‘tutorials point’,
      url: ‘http://www.tutorialspoint.com’,
      tags: [‘mongodb’, ‘database’, ‘NoSQL’],
      likes: 100
   },
 
   {
      title: ‘NoSQL Database’,
      description: ‘NoSQL database doesn’t have tables’,
      by: ‘tutorials point’,
      url: ‘http://www.tutorialspoint.com’,
      tags: [‘mongodb’, ‘database’, ‘NoSQL’],
      likes: 20,
      comments: [
         {
            user:’user1′,
            message: ‘My first comment’,
            dateCreated: new Date(2013,11,10,2,35),
            like: 0
         }
      ]
   }
])

 

Query document

>db.COLLECTION_NAME.find()

>db.mycol.find().pretty()

Advertisements
This entry was posted in MongoDB and tagged , , . Bookmark the permalink.