How to create a MongoDB database and collection

MongoDB FAQ: How do I create a MongoDB database?

To create a MongoDB database, follow these steps:

  1. “Use” the database.
  2. Create a collection in the database.
  3. Verify that you got what you wanted.

Short example

For example, to “use” a database named pizzas, start your mongo client and then issue this command:

use pizzas

Next, create a collection in this database. For instance, create a document in a customers collection like this:

db.customers.save({"firstName":"Alvin", "lastName":"Alexander"})

Next, verify that your document was created with this command:

db.customers.find()

You should see output from MongoDB showing that your document was created.

Complete example

Here’s what this looks like when I try it with my own MongoDB installation, including my commands and the output from MongoDB:

> use pizzas
switched to db pizzas

> db
pizzas

> db.customers.save({"firstName":"Alvin", "lastName":"Alexander"})

> db.customers.find()
{ "_id" : ObjectId("520e3cebf2b2417375cbc438"), "firstName" : "Alvin", "lastName" : "Alexander" }

> db
pizzas

Notice that I used the db command twice, and it showed I am in the pizzas database. After issuing these commands I can also issue the MongoDB show dbs command, and it shows my new pizzas database:

> show dbs
finance	0.203125GB
local	(empty)
pizzas	0.203125GB   <== the new 'pizzas' database
test	0.203125GB

If you needed to create a new MongoDB database, I hope these examples have been helpful.

Source: alvinalexander

Advertisements

Introduction to Mongoose

Mongoose is a JavaScript framework that is commonly used in a Node.js application with a MongoDB database. In this article, I am going to introduce you to Mongoose and MongoDB, and more importantly where these technologies fit in to your application.

Let’s start with MongoDB. MongoDB is a database that stores your data as documents. Most commonly these documents resemble a JSON-like structure:

A document then is placed within a collection. As an example, the above document example defines a user object. This user object then would typically be part of a collection called users.

One of the key factors with MongoDB is its flexibility when it comes to structure. Even though in the first example, the user object contained a firstName and lastName property, these properties are not required in every user document that is part of the users collection. This is what makes MongoDB very different from a SQL database like MySQL or Microsoft SQL Server that requires a strongly-defined database schema of each object it stores.

The ability to create dynamic objects that are stored as documents in the database is where Mongoose comes into play.

Mongoose is an Object Document Mapper (ODM). This means that Mongoose allows you to define objects with a strongly-typed schema that is mapped to a MongoDB document.

Mongoose provides an incredible amount of functionality around creating and working with schemas. Mongoose currently contains eight SchemaTypes that a property is saved as when it is persisted to MongoDB. They are:

  1. String
  2. Number
  3. Date
  4. Buffer
  5. Boolean
  6. Mixed
  7. ObjectId
  8. Array

Each data type allows you to specify:

  • a default value
  • a custom validation function
  • indicate a field is required
  • a get function that allows you to manipulate the data before it is returned as an object
  • a set function that allows you to manipulate the data before it is saved to the database
  • create indexes to allow data to be fetched faster

One thing worth noting is that Mongoose maintains a global connection object for us. Which means if you define mongoose connection in your project folder somewhere, you need not require/reinitiate/call it anywhere else in folder structure of your project.

Mongoose is a JavaScript framework, and I am going to use it in a Node.js application. If you already have Node.js installed, you can move on to the next step. If you do not have Node.js installed, I suggest you begin by visiting the Node.js Download page and selecting the installer for your operating system.

With Node.js set up and ready to go, I am going to create a new application and then install the Mongoose NPM Package.

With a command prompt that is set to where you wish your application to be installed, you can run the following commands:

For the initialization of my application, I left everything as their default values. Now I’m going to install the mongoose package as follows:

With all the prerequisites configured, let’s connect to a MongoDB database. I’ve placed the following code inside an index.js file because I chose that as the starting point for my application:

The first line of code includes the mongoose library. Next, I open a connection to a database that I’ve called mongoose_basics using the connect function.

For more:

http://mongoosejs.com/docs/guide.html

https://code.tutsplus.com/articles/an-introduction-to-mongoose-for-mongodb-and-nodejs–cms-29527

MongoDB Working Commands

Mongodb uses JavaScript interpreter like in browser. You can run commands like in Chrome DevTools on mongodb for insertion etc.

show dbs
> print(“test”)
test
> var arr=[‘1′,’2’]
> arr
[ “1”, “2” ]
> use learning_mongo
switched to db learning_mongo
> for(i=0;i<1000;i++){
… db.numbers.insert(
… {‘number’:i})}
WriteResult({ “nInserted” : 1 })
> db.numbers.count()
1000

 

db.numbers.find({‘number’:556})
{ “_id” : ObjectId(“5a5b7f5c5a887e7aadb86393”), “number” : 556 }

> db.numbers.find({‘number’:556}).explain()
{
“queryPlanner” : {
“plannerVersion” : 1,
“namespace” : “learning_mongo.numbers”,
“indexFilterSet” : false,
“parsedQuery” : {
“number” : {
“$eq” : 556
}
},
“winningPlan” : {
“stage” : “COLLSCAN”,
“filter” : {
“number” : {
“$eq” : 556
}
},
“direction” : “forward”
},
“rejectedPlans” : [ ]
},
“serverInfo” : {
“host” : “BLRSVAKA168443”,
“port” : 27017,
“version” : “3.2.10”,
“gitVersion” : “79d9b3ab5ce20f51c272b4411202710a082d0317”
},
“ok” : 1
}

db.numbers.find({‘number’:556}).explain(‘executionStats’)
{
“queryPlanner” : {
“plannerVersion” : 1,
“namespace” : “learning_mongo.numbers”,
“indexFilterSet” : false,
“parsedQuery” : {
“number” : {
“$eq” : 556
}
},
“winningPlan” : {
“stage” : “COLLSCAN”,
“filter” : {
“number” : {
“$eq” : 556
}
},
“direction” : “forward”
},
“rejectedPlans” : [ ]
},
“executionStats” : {
“executionSuccess” : true,
“nReturned” : 1,
“executionTimeMillis” : 0,
“totalKeysExamined” : 0,
“totalDocsExamined” : 1000,
“executionStages” : {
“stage” : “COLLSCAN”,
“filter” : {
“number” : {
“$eq” : 556
}
},
“nReturned” : 1,
“executionTimeMillisEstimate” : 0,
“works” : 1002,
“advanced” : 1,
“needTime” : 1000,
“needYield” : 0,
“saveState” : 7,
“restoreState” : 7,
“isEOF” : 1,
“invalidates” : 0,
“direction” : “forward”,
“docsExamined” : 1000
}
},
“serverInfo” : {
“host” : “BLRSVAKA168443”,
“port” : 27017,
“version” : “3.2.10”,
“gitVersion” : “79d9b3ab5ce20f51c272b4411202710a082d0317”
},
“ok” : 1
}

> db.numbers.createIndex({number:1})
{
“createdCollectionAutomatically” : false,
“numIndexesBefore” : 1,
“numIndexesAfter” : 2,
“ok” : 1
}

MongoDB Tutorials

How to install MongoDB in Mac:

download zip from this link https://www.mongodb.com/download-center?jmp=nav#community.
unzip it and copy on desktop
cd Desktop
sudo mv mongodb-osx-x86_64-3.6.1 /usr/local/mongodb
cd /usr/local/mongodb – use ‘ls’ to check folders in it
sudo mkdir -p /data/db
cd /data/db – use ‘pwd’ to check present working directory and confirm whether you are in db folder or not
whoami – to check your username
sudo chown svaka1 /data/db – change permissions to folder
go to home directory using ‘cd’ and hit enter. also check ‘pwd’ to confirm
ls -l – to show your list
ls -al – to show hidden list

check whether you can .bash_profile in terminal like shown below. if not use ‘touch .bash_profile’ to create one.

open .bash_profile

export MONGO_PATH=/usr/local/mongodb

export PATH=$PATH:$MONGO_PATH/bin

source .bash_profile – to reload bash profile with latest exports

close terminal and reopen it once again. This time we need 2 terminals to test our mongodb connection.

1st terminal – run ‘mongod’ command

2nd terminal – run ‘mongo’ command

Installing using brew

https://docs.mongodb.com/manual/tutorial/install-mongodb-on-os-x/

Any troubleshoot: https://www.moncefbelyamani.com/how-to-install-xcode-homebrew-git-rvm-ruby-on-mac/

Installation of mongodb in windows

Lets wrench the installation of mongodb today.

Note: Here in this tutorial we are using in different way like how mysql stores all projects in bin of mysql. We are doing the same by creating a common workspace where all the databases store in data folder of mongodb folder. You can maintain a separate db space in your project folder by following this previous tutorial

First download zip file(preferably) or exe file from mongodb

Once after install or extract of mongodb you will find the following files like shown below

29-05-2014 12-22-59

Now copy those files and create a directory in c drive and make sure the path should look like

c:/mongodb

Here paste the files. Before we startup some thing lets create a couple of directories name “data” and “log” in mongodb fodler. So finally it should look like

29-05-2014 12-25-43

Inside of data folder again create a folder name “db” //all database data will store here

Now install git in your machine in replacement of command prompt.

Hope the installation is complete now…lets step forward

goto c:/mongodb/ folder. right click on bin folder and click “Git Bash” as shown below

29-05-2014 12-34-19

Hope you can see gitbash prompt which resembles like cmd

Now we should define default directory,db path and log manually with commands as shown below

Note: ‘/’ or ‘\’ is very important here in command prompts coz unix style use ‘\’ which works in most cases.

29-05-2014 12-40-58

From the above image you can see the command we should type and hit enter to set default directory,log path, log appends(instead of overwriting in mongodb.log everytime) and to use rest services.

Now you can see log name “mongodb.log” as shown below

29-05-2014 12-43-52

Now go back to mongodb folder and right click bin folder again and click gitbash

Type mongo and hit enter. you can see its connected

29-05-2014 12-46-37

Thats it now you can check dbs by show dbs command and create collections and documents as you wish.

Now we need install mongodb as a window service else you will be figured out with an error showing connection failed.

For that you just need to append –install command to the above command where the command finally will be

> mongod –directoryperdb –dbpath c:/mongodb/data/db  –logpath c:/mongodb/log/mongodb.log –logappend –rest –install

Hit enter, with that it will create a service for us.

29-05-2014 12-55-18

Just type “net start mongoDB

29-05-2014 12-58-10

To verify whether mongodb started or not..click windows and type “services.msc” where you will find a wrench gear up icon..click on it and check whether mongodb is started or not.

With this we completed successfully installing and starting mongodb. Lets goto c:/mongodb/bin gitbash prompt and type “mongo”.

Show databases:

Now you can see databases by showdbs command

Create/switch to database:

create db by use database_name command (eg: use sathya will create a database and switches to that database).

Show collections:

show collections – will show the list of collections(tables in oracle)

db.createCollection(“collectionname”) – will create a collection in your database

Lets take an example to insert data in collections..Now i will create a table called employee and stores(create/update/delete) some records in it.

Create collection:

Eg: db.createCollection(“employee”);

the above command creates a employee collection(table) in db. Now lets insert some stuff in it.

Insert records:

db.employee.insert({name:”sathya”,dept:”computers”,technology:”html5″}) – hit enter

To check the record inserted or not..use db.employee.find() – this results an unorder/unformatted content. Lets put up some make up for this.. 😉

Find records:

use command – db.employee.find().pretty()

Find Only one field:

If you wish to find only one employee with particular name..

just type db.employee.findOne({name:”sathya”}) – this results only one employee with name sathya

Update command:

db.employee.update({oldname},{new name},{ upsert})

Eg: db.employee.update({name:”sathya”}.{name:”SathyaManoj”}.{upsert:true})

You can even modify different fields/columns by db.employee.update({name:”sathya”,dept:”computers”}.{name:”SathyaManoj”,dept:”IT”}.{upsert:true})

This will update the name sathya with SathyaManoj. And what this upsert does is..it will check for the name sathya to update, if it doesnt find it..then it will create a new one.

Now check it by using db.employee.find().pretty()

Delete command:

db.employee.remove({name:”sathya”}) – will remove the record from the collection.

What is mongodb? Basics of mongodb

MongoDB is a cross-platform, document oriented database that provides, high performance, high availability, and easy scalability. MongoDB works on concept of collection and document.

Database

Database is a physical container for collections. Each database gets its own set of files on the file system. A single MongoDB server typically has multiple databases.

Collection

Collection is a group of MongoDB documents. It is the equivalent of an RDBMS table. A collection exists within a single database. Collections do not enforce a schema. Documents within a collection can have different fields. Typically, all documents in a collection are of similar or related purpose.

Document

A document is a set of key-value pairs. Documents have dynamic schema. Dynamic schema means that documents in the same collection do not need to have the same set of fields or structure, and common fields in a collection’s documents may hold different types of data.

Below given table shows the relationship of RDBMS terminology with MongoDB

RDBMS MongoDB
Database Database
Table Collection
Tuple/Row Document
column Field
Table Join Embedded Documents
Primary Key Primary Key (Default key _id provided by mongodb itself)
Database Server and Client
Mysqld/Oracle mongod
mysql/sqlplus mongo

 

Sample document

Below given example shows the document structure of a blog site which is simply a comma separated key value pair.

{
   _id:ObjectId(7df78ad8902c)
   title:'MongoDB Overview', 
   description:'MongoDB is no sql database',by:'tutorials point',
   url:'http://www.tutorialspoint.com',
   tags:['mongodb','database','NoSQL'],
   likes:100, 
   comments:[{
         user:'user1',
         message:'My first comment',
         dateCreated:newDate(2011,1,20,2,15),
         like:0},{
         user:'user2',
         message:'My second comments',
         dateCreated:newDate(2011,1,25,7,45),
         like:5}]}

_id is a 12 bytes hexadecimal number which assures the uniqueness of every document. You can provide _id while inserting the document. If you didn’t provide then MongoDB provide a unique id for every document. These 12 bytes first 4 bytes for the current timestamp, next 3 bytes for machine id, next 2 bytes for process id of mongodb server and remaining 3 bytes are simple incremental value.

Any relational database has a typical schema design that shows number of tables and the relationship between these tables. While in MongoDB there is no concept of relationship

Advantages of MongoDB over RDBMS

  • Schema less : MongoDB is document database in which one collection holds different different documents. Number of fields, content and size of the document can be differ from one document to another.
  • Structure of a single object is clear
  • No complex joins
  • Deep query-ability. MongoDB supports dynamic queries on documents using a document-based query language that’s nearly as powerful as SQL
  • Tuning
  • Ease of scale-out: MongoDB is easy to scale
  • Conversion / mapping of application objects to database objects not needed
  • Uses internal memory for storing the (windowed) working set, enabling faster access of data

Why should use MongoDB

  • Document Oriented Storage : Data is stored in the form of JSON style documents
  • Index on any attribute
  • Replication & High Availability
  • Auto-Sharding
  • Rich Queries
  • Fast In-Place Updates
  • Professional Support By MongoDB

Where should use MongoDB?

  • Big Data
  • Content Management and Delivery
  • Mobile and Social Infrastructure
  • User Data Management
  • Data Hub

     

 External References:

http://www.tutorialspoint.com/mongodb/mongodb_tutorial.pdf

http://try.mongodb.org/

http://mongodb.github.io/node-mongodb-native/api-articles/nodekoarticle1.html

http://blog.ksetyadi.com/2011/10/nodejs-and-mongodb-a-beginners-approach/

http://www.ibm.com/developerworks/library/wa-notify-app/