This article mainly introduces Java operation MongoDB.
Development environment:
System:windows
Ide:eclipse, MyEclipse 8
Database:mongodb
To develop a dependent library:
JavaEE5, Mongo-2.5.3.jar, Junit-4.8.2.jar
First, preparatory work
1, first of all, download the MongoDB Java-supported driver package
Driver package Download Address: http://www.jb51.net/softs/41751.html
MongoDB Java-related support, technology: Http://www.mongodb.org/display/DOCS/Java+Language+Center
2, the following set up a Javaproject project, import download down the driver package. You can use MongoDB in Java with the following directory:
Java Operation MongoDB Example
Before this example you need to start the Mongod.exe service, after the startup, the following program can be successfully executed;
1, establish Simpletest.java, complete the simple MongoDB database operation
Mongo Mongo = new Mongo ();
This creates a MongoDB database connection object that is connected to the localhost address of the current machine by default, and the port is 27017.
DB db = Mongo.getdb ("test");
This allows you to obtain a database of test, which can function correctly if the database is not created in MongoDB. If you read the previous article, MongoDB can complete the addition of the data without creating the database. When added, without this library, MongoDB will automatically create the current database.
With DB, the next step is to get a "clustered set Dbcollection", which is done through the GetCollection method of the DB object.
Dbcollection users = db.getcollection ("users");
So we get a dbcollection, which is equivalent to the "table" of our database.
Query all data
Dbcursor cur = users.find ();
while (Cur.hasnext ()) {
System.out.println (Cur.next ());
}
Complete source
Package com.hoo.test;
Import java.net.UnknownHostException;
Import Com.mongodb.DB;
Import com.mongodb.DBCollection;
Import Com.mongodb.DBCursor;
Import Com.mongodb.Mongo;
Import com.mongodb.MongoException;
Import Com.mongodb.util.JSON; /** * <b>function:</b>mongodb Simple example * @author hoojo * @createDate 2011-5-24 pm 02:42:29 * @file SIMPLETEST.J Ava * @package com.hoo.test * @project MongoDB * @blog Http://blog.csdn.net/IBM_hoojo * @email hoojo_@126.com * @vers Ion 1.0 */public class SimpleTest {public static void main (string[] args) throws Unknownhostexception, Mongoexceptio
n {Mongo mg = new Mongo ();
Query all database for (String name:mg.getDatabaseNames ()) {System.out.println ("dbname:" + name);
DB db = Mg.getdb ("test");
Queries all clustered collections for (String Name:db.getCollectionNames ()) {System.out.println ("CollectionName:" + name);
Dbcollection users = db.getcollection ("users");
Query all the data dbcursor cur = users.find (); While (Cur.hasnext ())
{System.out.println (Cur.next ());
} System.out.println (Cur.count ());
System.out.println (Cur.getcursorid ());
System.out.println (json.serialize (cur));
}
}
2, complete the crud operation, first establish a Mongodb4crudtest.java, the basic test code is as follows:
Package com.hoo.test;
Import java.net.UnknownHostException;
Import java.util.ArrayList;
Import java.util.List;
Import Org.bson.types.ObjectId;
Import Org.junit.After;
Import Org.junit.Before;
Import Org.junit.Test;
Import Com.mongodb.BasicDBObject;
Import com.mongodb.Bytes;
Import Com.mongodb.DB;
Import com.mongodb.DBCollection;
Import Com.mongodb.DBCursor;
Import Com.mongodb.DBObject;
Import Com.mongodb.Mongo;
Import com.mongodb.MongoException;
Import com.mongodb.QueryOperators;
Import Com.mongodb.util.JSON; /** * <b>function:</b> Implementation of MongoDB CRUD operations * @author Hoojo * @createDate 2011-6-2 pm 03:21:23 * @file mongodb4c
Rudtest.java * @package com.hoo.test * @project MongoDB * @blog Http://blog.csdn.net/IBM_hoojo * @email hoojo_@126.com
* @version 1.0 */public class Mongodb4crudtest {private Mongo mg = null;
private DB DB;
Private dbcollection users;
@Before public void Init () {try {mg = new Mongo ();
MG = new Mongo ("localhost", 27017); } CatCH (unknownhostexception e) {e.printstacktrace ();
catch (Mongoexception e) {e.printstacktrace ();
//Get temp db; If not created by default, MongoDB will automatically create DB = Mg.getdb ("temp");
Get the users dbcollection; if not created by default, MongoDB automatically creates users = Db.getcollection ("users");
@After public void Destory () {if (MG!= null) mg.close ();
MG = null;
db = null;
users = null;
System.GC ();
public void print (Object o) {System.out.println (o);
}
}
3. Add operation
Before adding the operation, we need to write a query method to query all the data. The code is as follows:
/** * <b>function:</b> query all data * @author Hoojo * @createDate 2011-6-2 03:22:40
* * private void Queryall () {print ("Query all data for users:");
DB cursor Dbcursor cur = users.find ();
while (Cur.hasnext ()) {print (Cur.next ());
@Test public void Add () {//First query all data Queryall ();
Print ("Count:" + users.count ());
DBObject user = new Basicdbobject ();
User.put ("name", "Hoojo");
User.put ("Age", 24);
Users.save (user) is saved, GETN () Gets the number of rows affected//print (users.save (user). GETN ());
Expand Fields, add fields at will, and do not affect existing data user.put ("Sex", "male");
Print (Users.save (user). GETN ());
Add multiple data, passing the Array object print (Users.insert (user, new Basicdbobject ("name", "Tom")). GETN ());
Add list list<dbobject> list = new arraylist<dbobject> ();
List.add (user);
DBObject user2 = new Basicdbobject ("name", "Lucy");
User.put ("Age", 22);
List.add (User2);
Add the List collection print (Users.insert (list). GETN ());
Query the data to see if the Add success print ("Count:" + users.count ());
Queryall (); }
4. Delete data
@Test public
Void Remove () {
queryall ();
Print (Delete id = 4de73f7acd812d61b4626a77:) + users.remove (new Basicdbobject ("_id", New ObjectId (" 4de73f7acd812d61b4626a77 ")). GETN ());
Print ("Remove Age >=:" + users.remove (New Basicdbobject ("Age", New Basicdbobject ("$gte")). GETN ());
5, modify the data
@Test public
Void Modify () {
print (modify: + users.update) (New Basicdbobject ("_id", New ObjectId (" 4dde25d06be7c53ffbd70906 ")), New Basicdbobject (" Age ",") "). GETN ());
Print ("Modify:" + users.update (
new Basicdbobject ("_id", New ObjectId ("4dde2b06feb038463ff09042")),
New Basicdbobject ("Age", 121),
true,//If the database does not exist, add
false//multiple modifications
). GETN ());
Print ("Modify:" + users.update (
new Basicdbobject ("name", "haha"),
new Basicdbobject ("name", "Dingding"),
true,//If the database does not exist, add
True//false to modify only the first day, true if there are more than one
. GETN ());
When the database does not exist, do not modify, do not add data, when more than one data will not modify
//print ("Modify multiple:" + coll.updatemulti (New Basicdbobject ("_id", New ObjectId (" 4dde23616be7c19df07db42c ")), new Basicdbobject (" name "," 199 ")));
6. Query data
@Test public void query () {//query for All//queryall (); Query id = 4de73f7acd812d61b4626a77 Print ("Find id = 4de73f7acd812d61b4626a77:" + users.find (New Basicdbobject ("_id", new
ObjectId ("4de73f7acd812d61b4626a77")). ToArray ());
Query age = Print (' Find age =: ' + users.find (new Basicdbobject ("Age"). ToArray ()); Query Age >= Print ("Discovery Age >=:" + users.find (New Basicdbobject ("Age", New Basicdbobject ("$gte")). Toarra
Y ());
Print ("Find age <=:" + users.find (New Basicdbobject ("Age", New Basicdbobject ("$lte")). ToArray ());
Print ("Query age!=25:" + users.find (New Basicdbobject ("Age", New Basicdbobject ("$ne")). ToArray ()); Print (query age in 25/26/27:) + users.find (New Basicdbobject ("Age", New Basicdbobject (queryoperators.in, new int[] {25, 26,
)). ToArray ()); Print (query age isn't in 25/26/27: + users.find (New Basicdbobject ("Age", New Basicdbobject (Queryoperators.nin, new int[] {25,
)). ToArray ()); Print ("Query Age exists sort:" + users.find (nEW Basicdbobject ("Age", New Basicdbobject (Queryoperators.exists, True)). ToArray ());
Print (query Age property only: + Users.find (NULL, New Basicdbobject ("Age", true)). ToArray ());
Print ("Check attributes only:" + users.find (null, New Basicdbobject ("Age", true), 0, 2). ToArray ());
Print ("Check attributes only:" + users.find (null, New Basicdbobject ("Age", true), 0, 2, bytes.queryoption_notimeout). ToArray ());
Query only one piece of data, many go to the first print ("FindOne:" + users.findone ());
Print ("FindOne:" + users.findone (New Basicdbobject ("Age", 26));
Print ("FindOne:" + users.findone (New Basicdbobject ("Age"), new Basicdbobject ("name", true));
Query modification, delete print ("Findandremove query age=25 data, and delete:" + users.findandremove (New Basicdbobject ("Age", 25)); Query for AGE=26 data and modify the value of name to ABC print ("Findandmodify:" + users.findandmodify (New Basicdbobject ("Age"), new
Basicdbobject ("name", "ABC")); Print ("findandmodify:" + users.findandmodify (New Basicdbobject ("Age", 28),//query age=28 data new Basicdbobject ("name", T Rue),///Query Name property new BasicdboBject ("Age", true),//Sort by age false,//delete, true means delete new Basicdbobject ("name", "ABC"),//modified value, change name to ABC true, t
Rue));
Queryall ();
}
MongoDB does not support federated queries, subqueries, which require us to do it ourselves in the program. The result set of the query is filtered in the Java query as needed.
7, other operations
public void Testothers () {
DBObject user = new Basicdbobject ();
User.put ("name", "Hoojo");
User.put ("Age",);
JSON Object converts
print ("Serialize:" + json.serialize (user));
Deserialization
Print ("Parse:" + json.parse ("{\ name\": \ "hoojo\", \ "age\":));
Print ("Judge if temp collection exists:" + db.collectionexists ("temp"));
If not present, create if
(!db.collectionexists ("temp")) {
DBObject options = new Basicdbobject ();
Options.put ("size");
Options.put ("capped");
Options.put ("Max");
Print (Db.createcollection ("Account", options);
}
Set DB to read-only
db.setreadonly (true);
Read-only cannot write to data
db.getcollection ("Test"). Save (user);
}
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.