CRUD operations on Java for MONGDB

Source: Internet
Author: User

Package MongoDB;

Import java.net.UnknownHostException;
Import java.util.List;

Import Com.mongodb.BasicDBObject;
Import Com.mongodb.DB;
Import com.mongodb.DBCollection;
Import Com.mongodb.DBCursor;
Import Com.mongodb.Mongo;

public class Mongocrud {

public static void Main (string[] args) {
try {

This creates a MongoDB database connection object, which is connected by default to the current machine's localhost address, and the port is 27017.
Mongo Mongo = new Mongo ();

You can also connect to a database like this

Mongoclient mongoclient = new Mongoclient ("localhost", 27017);

Get all database names
list<string> list = Mongo.getdatabasenames ();
for (String dbname:list) {
System.out.println ("databasename=" +dbname);
}

Get the database if not, create
DB db = Mongo.getdb ("MyTest");

Get all the table names for the DB database (represented here in a collection)
set<string> set = Db.getcollectionnames ();
for (String String:set) {
System.out.println ("tablesname=" +string);
}


Get the table for the database if it is not, create
Dbcollection coll = db.getcollection ("Mytables");

The first way to insert JSON-formatted data with Basicdbobject
Basicdbobject DbObject1 = new Basicdbobject ();
Dbobject1.append ("id", 1). Append ("name", "Jerry"). Append ("Age", "at"). Append ("Job", "programmer"). Append ("Address", "Shenzhen");

Basicdbobject dbObject2 = new Basicdbobject ();
Dbobject2.put ("id", 2);
Dbobject2.put ("name", "Enen");
Dbobject2.put ("Age", 22);
Dbobject2.put ("Address", "Huizhou");
Dbobject2.put ("Jerry", DbObject1);
Coll.insert (DBOBJECT2);

The second use of Basicdbobjectbuilder

Basicdbobjectbuilder Documentbuilder = Basicdbobjectbuilder.start ()
. Add ("Database", "Mkyongdb")
. Add ("Table", "hosting");
Basicdbobjectbuilder documentbuilderdetail = Basicdbobjectbuilder.start ()
. Add ("Records", "99")
. Add ("Index", "Vps_index1")
. Add ("Active", "true");
Documentbuilder.add ("Detail", documentbuilderdetail.get ());
Coll.insert (Documentbuilder.get ());

The third use of the Map object

Map documentmap =new HashMap ();
Documentmap.put ("Database", "mkyongdb");
Documentmap.put ("Table", "hosting");
Map documentmapdetail =new HashMap ();
Documentmapdetail.put ("Records", "99");
Documentmapdetail.put ("index", "vps_index1");
Documentmapdetail.put ("Active", "true");
Documentmap.put ("detail", documentmapdetail);
Coll.insert (New Basicdbobject (Documentmap));

The fourth approach, the simplest, is to insert JSON-formatted data directly
String json = "{' database ': ' Mkyongdb ', ' table ': ' Hosting '," +
"' detail ': {' Records ':", ' Index ': ' Vps_index1 ', ' active ': ' True '}}} ";
DBObject dbobject = (dbobject) json.parse (JSON);
Coll.insert (DBObject);

Querying all the data
dbcursor cursor = Coll.find ();
System.out.println (Cursor.count ());
while (Cursor.hasnext ()) {
System.out.println (Cursor.next ());
}

Delete Find First delete
DBObject FindOne = Coll.findone ();
Coll.remove (FindOne);

System.out.println ("------------------------before modification");

DBObject updatecondition=new basicdbobject ();
Updatecondition.put ("name", "Enen");

DBObject updatedvalue=new basicdbobject ();
Updatedvalue.put ("Age", 3);
Updatedvalue.put ("Address", "Boss");

DBObject updatesetvalue=new basicdbobject ("$set", Updatedvalue);
Coll.update (Updatecondition, updatesetvalue,true,false);//The following two parameter settings, the first one is when the where condition does not exist, insert data. The next one is whether to modify multiple records.
System.out.println ("Modified---------------");
Dbcursor find = Coll.find ();
while (Find.hasnext ()) {
DBObject next = Find.next ();
System.out.println (next);
}

SYSTEM.OUT.PRINTLN (json.serialize (cursor));

} catch (Unknownhostexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
}

Here because there is no time, all is not extracted to the method, through the method call, squeezed in a main class, there is time to refactor him.

CRUD operations on Java for MONGDB

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.