Previous Article: getting started with MongoDB
Http://blog.csdn.net/rjfxd/article/details/12108909
I. Preparations
1. Create a maven project and add the required Dependencies
<Dependency>
<GroupId> junit </groupId>
<ArtifactId> junit </artifactId>
<Version> 4.10 </version>
<Scope> test </scope>
</Dependency>
<Dependency>
<GroupId> org. mongodb </groupId>
<ArtifactId> mongo-java-driver </artifactId>
<Version> 2.11.3 </version>
</Dependency>
Of course, you can also create a java project, download and copy the jar file to lib.
2. Enable the mongo service and create a test class for testing.
Ii. complete source code is as follows:
package com.shxt.mongo;
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.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import com.mongodb.util.JSON;
* *
*Crud of mongdb
*@ author fan Xiaodong
* @ClassName: TestMongo
* @Version 1.0
* @ModifiedBy
* @Copyright shxt
*@ date 2013-9-27 08:21:49 PM
* @description
* /
public class TestMongo {
private Mongo mg = null;
private DB db;
private DBCollection users;
@Before
public void setUp() throws UnknownHostException {
//Create a mongodb database connection object
mg=new MongoClient("localhost", 27017);
//Authentication mode login (if authentication module is not set, login directly)
//To log in and validate the module, enter 1 - > Mongo 2 - > use admin 3 - > db.adduser ("root", "root123"); 4 - > db.auth ("root", "root123");
DB admin=mg.getDB("admin");
boolean bool =admin.authenticate("root", "root123".toCharArray());
If (bool) {
//login success
//Get a test database. If the database does not exist, it will be created automatically
db=mg.getDB("test");
}
//Get a collection dbcollection, which is equivalent to our database table
users = db.getCollection("users");
}
@Test
public void testQuery() {
//Query all databases
for (String name : mg.getDatabaseNames()) {
System.out.println("dbName: " + name);
}
//Query all aggregate collections
for (String name : db.getCollectionNames()) {
System.out.println("collectionName: " + name);
}
//Query all data
DBCursor cur = users.find();
while (cur.hasNext()) {
System.out.println(cur.next());
}
/ / others
System.out.println(cur.count());
System.out.println(users.count());
System.out.println(cur.getCursorId());
System. Out. Println (JSON. Serialize (cur)); / / JSON object transformation
}
@Test
public void testQuery2(){
//Query by ID
List<DBObject> list=users.find(new BasicDBObject("_id", new ObjectId("5243871a0609f38c8a7a5ccd"))).toArray();
System.out.println(list.get(0).get("name"));
//According to the age query, start from the first item and take three pieces of data
BasicDBObject user = new BasicDBObject();
user.put("age", new BasicDBObject("$gte", 20));
DBCursor cur=users.find(user).skip(0).limit(3);
System.out.println(cur.count());
while (cur.hasNext()) {
System.out.println(cur.next());
}
//Query age! = 25
//users.find(new BasicDBObject("age", new BasicDBObject("$ne", 25))).toArray();
//Query age in 25 / 26 / 27
//users.find(new BasicDBObject("age", new BasicDBObject(QueryOperators.IN, new int[] { 25, 26, 27 }))).toArray();
//Query age not in 25 / 26 / 27
//users.find(new BasicDBObject("age", new BasicDBObject(QueryOperators.NIN, new int[] { 25, 26, 27 }))).toArray();
//Query data with age
//users.find(new BasicDBObject("age", new BasicDBObject(QueryOperators.EXISTS, true))).toArray();
//Query only age property
//users.find(null, new BasicDBObject("age", true)).toArray();
//Query only one piece of data, take the first piece of multiple pieces
//users.findOne();
//users.findOne(new BasicDBObject("age", 26));
//users.findOne(new BasicDBObject("age", 26), new BasicDBObject("name", true));
//Query data with age = 25 and delete
//users.findAndRemove(new BasicDBObject("age", 25));
//Query the data with age = 26, and change the value of name to ABC
//users.findAndModify(new BasicDBObject("age", 26), new BasicDBObject("name", "abc"));
}
@Test
public void testAdd() {
DBObject user = new BasicDBObject();
user.put("name", "fxd");
user.put("age", 21);
User. Put ("sex", "male");
users.save(user);
//See if it is added successfully
DBCursor cur = users.find();
while (cur.hasNext()) {
System.out.println(cur.next());
}
}
@Test
public void testAdd2() {
Dbobject user1 = new basicdbobject ("name", "Zhang San");
DBObject user2 = new BasicDBObject("age",20);
users.insert(user1,user2);
//See if it is added successfully
DBCursor cur = users.find();
while (cur.hasNext()) {
System.out.println(cur.next());
}
}
@Test
public void testAdd3() {
Dbobject user1 = new basicdbobject ("name", "Zhang San");
DBObject user2 = new BasicDBObject("age",20);
List<DBObject> list = new ArrayList<DBObject>();
list.add(user1);
list.add(user2);
users.insert(list);
//See if it is added successfully
DBCursor cur = users.find();
while (cur.hasNext()) {
System.out.println(cur.next());
}
}
@Test
public void testRemove(){
users.remove(new BasicDBObject("_id", new ObjectId("524378680609ad5717421c6a")));
//users.remove(new BasicDBObject("age", new BasicDBObject("$gte", 24)));
}
@Test
public void update(){
//=update users set age=17 where name='fxd';
users.update(
new BasicDBObject("name","fxd"),//new BasicDBObject().append("name","fxd"),
new BasicDBObject("$set" ,new BasicDBObject("age",17)),
False, / / if age field does not exist in users, update or not. False means not update
False / / only the first item is modified. True means multiple items are modified
);
}
@Test
public void update2(){
//For batch modification, users. Update() can also be used to change the fourth parameter to true
//=update users set age=age+10 where name='fxd';
users.updateMulti(
new BasicDBObject().append("name","fxd"),
new BasicDBObject("$inc",new BasicDBObject("age", 10))
);
}
@After
public void tearDown() {
if (mg != null) {
if (db != null) {
//End transaction request of Mongo database
Try {
db.requestDone();
} catch (Exception e) {
e.printStackTrace();
}
}
Try {
Mg.close ();
} catch (Exception e) {
e.printStackTrace();
}
Mg = null;
DB = null;
}
}
}
Refer:
Http://www.cnblogs.com/hoojo/archive/2011/06/02/2068665.html