所用mongodb版本:2.6.6 windows版
所用java驱动包:mongo-java-driver-2.6.5.jar
MongoTest.java
package mongodb;
import org.junit.Test;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
public class MongoTest {
@Test
public void findAll() throws Exception{
Mongo mongo=new Mongo("127.0.0.1", 27017);
DB db = mongo.getDB("test");
DBCollection dbCollection = db.getCollection("users");
DBCursor dbCursor = dbCollection.find();
while(dbCursor.hasNext()){
DBObject dbObject = dbCursor.next();
System.out.println(dbObject.toString());
}
}
@Test
public void limitFind() throws Exception{
Mongo mongo=new Mongo("127.0.0.1", 27017);
DB db = mongo.getDB("test");
DBCollection dbCollection = db.getCollection("users");
DBCursor dbCursor = dbCollection.find().limit(3).skip(1);
while(dbCursor.hasNext()){
DBObject dbObject = dbCursor.next();
System.out.println(dbObject.toString());
}
}
@Test
public void findByCondition() throws Exception{
Mongo mongo=new Mongo("127.0.0.1", 27017);
DB db = mongo.getDB("test");
DBCollection dbCollection = db.getCollection("users");
DBObject name=new BasicDBObject();
name.put("name", "zhangsan");
DBObject age=new BasicDBObject();
age.put("age", 30);
BasicDBList conitionList=new BasicDBList();
conitionList.add(name);
conitionList.add(age);
DBObject searchdb=new BasicDBObject();
searchdb.put("$and", conitionList);
// DBObject condition=new BasicDBObject();
// condition.put("$gt", 30);
// DBObject age=new BasicDBObject();
// age.put("age", condition);
DBCursor dbCursor = dbCollection.find(searchdb);
while(dbCursor.hasNext()){
DBObject dbObject = dbCursor.next();
System.out.println(dbObject.toString());
}
}
@Test
public void insert() throws Exception{
Mongo mongo=new Mongo("127.0.0.1", 27017);
DB db = mongo.getDB("test");
DBCollection dbCollection = db.getCollection("users");
DBObject dbObject=new BasicDBObject();
dbObject.put("name", "zhangsan3");
dbObject.put("age", 303);
dbCollection.insert(dbObject);
findAll();
}
@Test
public void remove() throws Exception{
Mongo mongo=new Mongo("127.0.0.1", 27017);
DB db = mongo.getDB("test");
DBCollection dbCollection = db.getCollection("users");
DBObject dbObject=new BasicDBObject();
dbObject.put("name", 30);
dbCollection.remove(dbObject);
findAll();
}
@Test
public void update() throws Exception{
Mongo mongo=new Mongo("127.0.0.1", 27017);
DB db = mongo.getDB("test");
DBCollection dbCollection = db.getCollection("users");
DBObject qObject=new BasicDBObject();
qObject.put("name", "小乔");
DBObject oObject=new BasicDBObject();
oObject.put("name", "zhengpengqiqo");
oObject.put("age", 20);
dbCollection.update(qObject, oObject);
findAll();
}
}