MongoDB : Java program to do basic crud operation

Sample Java program to connect MongoDb and perform Crud Operations.

Copy paste, run and learn ūüėČ

note :- Please ensure you have installed mongo dependency using jar, github or mvn

 

package com.premaseem.core;

import com.mongodb.*;

import java.util.Date;

/**
 * Java + MongoDB Crud operation example
 *
 */
public class App {
    public static void main(String[] args) {

        try {

            /**** Connect to MongoDB ****/
            // Since 2.10.0, uses MongoClient
            MongoClient mongo = new MongoClient("localhost", 27017);

            // or, to connect to a replica set, with auto-discovery of the primary, supply a seed list of members
//            MongoClient mongoClient = new MongoClient(Arrays.asList(new ServerAddress("localhost", 27017),
//                    new ServerAddress("localhost", 27018),
//                    new ServerAddress("localhost", 27019)));

            /**** Get database ****/
            // if database doesn't exists, MongoDB will create it for you
            DB db = mongo.getDB("testdb");

            /**** Get collection / table from 'testdb' ****/
            // if collection doesn't exists, MongoDB will create it for you
            DBCollection table = db.getCollection("user");

            /**** Insert ****/
            // create a document to store key and value
            BasicDBObject document = new BasicDBObject();
            document.put("name", "premaseem");
            document.put("age", 30);
            document.put("createdDate", new Date());
            table.insert(document);

            /**** Find and display ****/
            BasicDBObject searchQuery = new BasicDBObject();
            searchQuery.put("name", "premaseem");

            DBCursor cursor = table.find(searchQuery);

            while (cursor.hasNext()) {
                System.out.println(cursor.next());
            }

            /**** Update ****/
            // search document where name="premaseem" and update it with new values
            BasicDBObject query = new BasicDBObject();
            query.put("name", "premaseem");

            BasicDBObject newDocument = new BasicDBObject();
            newDocument.put("name", "premaseem-updated");

            BasicDBObject updateObj = new BasicDBObject();
            updateObj.put("$set", newDocument);

            table.update(query, updateObj);

            /**** Find and display ****/
            BasicDBObject searchQuery2
                    = new BasicDBObject().append("name", "premaseem-updated");

            DBCursor cursor2 = table.find(searchQuery2);

            while (cursor2.hasNext()) {
                System.out.println(cursor2.next());
            }

            /**** Done ****/
            System.out.println("Done");

        }  catch (MongoException e) {
            e.printStackTrace();
        }

    }
}

MongoDB : Exporting JSON with mongoexport

This will export a JSON representation of the database. Note that as a rule – particularly for backing up or moving data – MongoDB recommends the “dump and restore” approach as BSON can contain more rich data than JSON. Nevertheless, mongoexport still has its uses, sometimes a JSON representation of the data is very useful – it’s what we’ve been using so far in the application development.

Basic output to console

Need to specify the name of the database –db and the collection –collection to export. Restoring dumped data with MongoRestore Inserts only, no updates Exporting JSON with mongoexport

Basic output to console

> mongoexport –db meantest –collection tech

Send to a file

> mongoexport –db meantest –collection tech –out MEAN/api/data/tech.json

Create as array

> mongoexport –db meantest –collection tech –out MEAN/api/data/tech.json –jsonArray

Make output pretty

> mongoexport –db meantest –collection tech –out MEAN/api/data/tech.json –jsonArray –pretty

 

MongoDB : How to take export a database using mongo dump

We need to take database backup or have to export specific database in  mongo

This command will export specific databases in mongo and export to home folder /dump

> mongodump –db testDatabase

# to compress in zip file and folder

> mongodump –db testDatabase ¬† –gzip

cd ~/dump

 

 

This command will restore or import specific db

>mongorestore –db testDatabase ¬† –gzip ¬†~/dump/testDatabase

 

With auth you can take dump as

mongodump -h 10.10.10.10¬†-p 27017 -d dbName -u “user” -p “password” –excludeCollectionsWithPrefix=system

and restore as

mongorestore -d dbName¬†–dir=dbDir

Note :

There command should be run from command prompt / shell and not from mongo sheel.

Mongo restroe does not update existing collections

MongoDB : Normalize Database reference (DBRefs)

The joy of a Document database is that it eliminates lots of Joins. Your first instinct should be to place as much in a single document as you can. Because MongoDB documents have structure, and because you can efficiently query within that structure there is no immediate need to normalize data like you would in SQL. In particular any data that is not useful apart from its parent document should be part of the same document.

This is not so much a “storage space” issue as it is a “data consistency” issue. If many records will refer to the same data it is more efficient and less error prone to update a single record and keep references to it in other places.

DBRef documents resemble the following document:

{ "$ref" : <value>, "$id" : <value>, "$db" : <value> }

Consider a document from a collection that stored a DBRef in a creator field:

{
  "_id" : ObjectId("5126bbf64aed4daf9e2ab771"),
  // .. application fields
  "creator" : {
                  "$ref" : "creators",
                  "$id" : ObjectId("5126bc054aed4daf9e2ab772"),
                  "$db" : "users"
               }
}

The DBRef in this example points to a document in the creators collection of the users database that has ObjectId("5126bc054aed4daf9e2ab772") in its _id field.

Consider the following operation to insert two documents, using the _id field of the first document as a reference in the second document:

original_id = ObjectId()

db.places.insert({
    "_id": original_id,
    "name": "Broadway Center",
    "url": "bc.example.net"
})

db.people.insert({
    "name": "Erin",
    "places_id": original_id,
    "url":  "bc.example.net/Erin"
})

Then, when a query returns the document from the people collection you can, if needed, make a second query for the document referenced by the places_id field in the places collection.

Reference link for details : https://docs.mongodb.com/manual/reference/database-references/

Certification : MongoDB for Database Adminstrators ‚Äď M102

Hi Friends,

I feel pleasure to share that I have taken one more step towards MongoDb expertise by successfully finishing yet another certification course for Mongo DB as database administrator ūüėČ Previous certificate was M101P which was focused on developer’s aspect of mongoDb, this certificate is M102 – which was focused on database administrator’s aspect of MongoDb.
DBA_Database_Administrator_certificate_for_mongo_DB_Aseem_Jain_2016
It was a 2 month long course and I finished this with 90%.
This certificates enabled me to set up production level replica sets, shards, fail overs, indexes, performance tuneups, back up and recovery, data migration and several other complex tasks.

Mac : Installing Mysql on mac using brew

Look, if you just want to try out mysql only for learning then there is not need for local installation, you can try it out free at this site : http://demo.phpmyadmin.net/master-config/

If you want to install Mysql on you mac machine then follow below steps :

  1. Install mysql with brew install mysql
  2. Start mysql with mysql.server start
  3. Connect mysql with mysql -uroot 
  4. Stop mysql with mysql.server stop

 

Note :

To have launchd start mysql at login:

  ln -sfv /usr/local/opt/mysql/*.plist ~/Library/LaunchAgents

Then to load mysql now:

  launchctl load ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist

Or, if you don’t want/need launchctl, you can just run:

$   mysql.server start

$ mysql -uroot

$ mysql.server stop

Once Mysql is installed you can check port number using below command

mysql> SHOW GLOBAL VARIABLES LIKE ‘PORT’;

+—————+——-+

| Variable_name | Value |

+—————+——-+

| port          | 3306  |

+—————+——-+

1 row in set (0.00 sec)

MongoDB : mongovue a windows desktop GUI client for easy no sql data visualization

http://www.mongovue.com/

MongoVUE is an innovative MongoDB desktop application for Windows OS that gives you an elegant and highly usable GUI interface to work with MongoDB. Now there is one less worry in managing your web-scale data.

MongoVUE makes it a very simple to see and visualize your data. It gives you 3 different views of it ‚Äď TreeView, TableView and TextView. If you are from RDBMS (SQL) back ground you will feel at home with Table View of MongoDB (no sql).