Vous êtes sur la page 1sur 10

Experiment No: Group B(18)

Title: Connectivity with MongoDB - Java Connectivity.


Aim: Connectivity with MongoDB using any Java application(Two Tier).
Prerequisites:

Basic

of

MongoDB(Basic

commands),

Basic

of

Java(Classes MongoDB library)


Objectives: Ability of problem solving using advanced databases
techniques and
tools
Theory:
Installation
Before we start using MongoDB in our Java programs, we need to make
sure that we have MongoDB JDBC Driver and Java set up on the machine.
You need to download the jar from the path
http://central.maven.org/maven2/org/mongodb/mongojava-driver/2.11.3/.
Make sure to download latest release of it.
You need to include the mongo.jar into your classpath.
Connect to database:
To connect database, you need to specify database name, if
database doesn't exist then mongodb creates it automatically.
Classes in mongo-java-driver.jar:
1.DB:(public abstract class DB extends
Object) Package:
com.mongodb.DB
An abstract class that represents a logical database on a server

Constructor
s:
DB( Mongo mongo, String name)
Method Summary:
Modifier
and

Descriptio
n

Method

Type
void

addOption(int option)

Adds the give option

DBCollectio
n

Gets a collection with a


getCollection( String name) given
name.

Set<
String>

getCollectionFromString
(String s)

Gets a collection with a


given
name.

Mongo

Gets the Mongo


instance

getMongo()

createCollection( String
DBCollection name,
DBObject options)
boolean

Creates a collection with


a
given name and
options

authenticate( String
username,

Authenticat
e
database user

char[] password)

with given username and


password

void

dropDatabase()

Drops this database

2. DBCollection: (public abstract class DBCollection extends Object)


Package: com.mongodb.DBCollection
This class provides a skeleton implementation of a database collection

Constructors :
DBCollection(DB base, String name)
Method Summary:
Modifier

Method

Description

and Type

long

count()

returns the number of documents


in
this collection.

void

createIndex( DBObject
keys)
calls
createIndex(com.mongodb.DB
Object,
com.mongodb.DBObject)

with

default index options


void

DBCursor

drop()

Drops (deletes) this


collection.

find( DBObject ref)

Queries for an object in this


collection.

WriteResu
insert( DBObject... arr)
lt

Saves document(s) to the


database.

WriteResu
remove( DBObject o)
lt

calls
remove(com.mongodb.DBObje
ct,
com.mongodb.WriteConc
ern)
the default WriteConcern

3. MongoClient: (public class MongoClient


extends Mongo) Package:
com.mongodb.MongoClient
A MongoDB client with internal connection pooling. For most
applications, you should have one MongoClient instance for the entire
JVM.
Constructors :

with

MongoClient() : Creates an instance based on a (single) mongodb node


(localhost,
default port).
MongoClient( String host, int port): Creates a Mongo instance based
on a (single)
mongodb node.
Parameters:
host - the database's host address
port - the port on which the database is running

4. BasicDBObject: (public class BasicDBObject extends


BasicBSONObject implements DBObject)
Package: com.mongodb.BasicDBObject
A basic implementation of bson object that is mongo specific. A
DBObject can be created as follows, using this class:
DBObject obj = new
BasicDBObject(); obj.put( "foo",
"bar" );

Constructors :
public BasicDBObject(int size): creates an empty object
public BasicDBObject(int size): creates an empty object

5. DBCursor: (public class DBCursor extends Object implements


Iterator<DBObject>, Iterable<DBObject>, Closeable)
Package: com.mongodb. DBCursor
An iterator over database results. Doing a find() query on a
collection returns a DBCursor thus :
DBCursor cursor =
collection.find( query );
if( cursor.hasNext() )

DBObject obj = cursor.next();

Constructors :
public DBCursor(DBCollection collection,DBObject q,
DBObject k, ReadPreference preference)): Initializes
a new database cursor

Method Summary:
Modifier

and Method

Description

Type
public boolean

hasNext()

Checks if there is another


object
available

public
DBObject

next()

Returns the object the cursor is


at
and moves the cursor ahead
by
one.

public void
public int

remove()
length()

Not implemented
pulls back all items into an
array
and returns the number of
objects.
Note: this can be resource
intensive

Conclusion:
Here we performed Connectivity with MongoDB using any Java
application.

Assignment B-10 Code:


import
com.mongodb.*;
import
java.util.Arrays;
public class Mongo
{
public static void main( String args[] )
{
try
{

//##########################Connect to
Database################# MongoClient mongoClient = new
MongoClient( "localhost" , 27017 );

DB db =
mongoClient.getDB( "MandarMokashi");
System.out.println("Connect to database
successfully");
//###########################Create
Collection################# DBCollection coll =
db.createCollection("Nilesh", null);
System.out.println("Collection created successfully");
//#########################Inserting
Document#################

BasicDBObject doc = new BasicDBObject("Name", "Mandar


Mokashi"). append("Qualification", "M-Tech").
append("Post","Ass. Proffessor").
append("WebSite", "http://www.dypic.in");
coll.insert(doc);
System.out.println("Document inserted successfully");
//######################Display All Document In
Collection########

DBCursor cursor =
coll.find(); int i=1;
while (cursor.hasNext())
{
System.out.println("Inserted Document: "+i);
System.out.println(cursor.next());
i++;
}
//######################Removeing
Document################## DBCollection coll1 =
db.getCollection("mycol");
DBObject myDoc =
coll1.findOne();

coll1.remove(myDoc);

DBCursor cursor1 =
coll.find(); i=1;
while (cursor1.hasNext())
{
System.out.println("Inserted Document: "+i);
System.out.println(cursor1.next());
i++;
}
}catch(Exception e)
{
}
}
}
Output:
Connect to database successfully
Collection created successfully
Document inserted successfully
Inserted Document: 1
{ "_id" : { "$oid" : "45982d53e4b08e9fe2dd47bc"} , "Name" :
"Nilesh Korade" ,
"Qualification" : "M-Tech" , "Post" :
"http://www.dypic.in"

Vous aimerez peut-être aussi