import com.mongodb.MongoClient;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;
import java.net.UnknownHostException;
import java.util.List;
import java.util.Set;
// http://api.mongodb.org/java/2.12/
// http://central.maven.org/maven2/org/mongodb/mongo-java-driver/
public class MongoTest {
/**
* @author Man_hua
* @param args
* @throws UnknownHostException
*/
public static void main(String[] args) {
//connect
MongoClient mongoClient;
try {
mongoClient = new MongoClient( "localhost" , 27017 );
//打印所有数据库
print("打印所有数据库");
for (String s : mongoClient.getDatabaseNames()) {
System.out.println(s);
}
//连接数据库
DB db = mongoClient.getDB( "mydb" );
//显示所有collection
print("显示所有collection");
Set<String> colls = db.getCollectionNames();
for (String s : colls) {
System.out.println(s);
}
//进入下一级
DBCollection coll = db.getCollection("testData");
//单个插入
BasicDBObject doc = new BasicDBObject("name", "MongoDB").
append("type", "database").
append("count", 1).
append("info", new BasicDBObject("x", 203).append("y", 102));
coll.insert(doc);
//多个插入
for (int i=0; i < 100; i++) {
coll.insert(new BasicDBObject("i", i));
}
//获得记录计数
print("获得记录计数");
System.out.println(coll.getCount());
//查询一个
print("查询一个");
DBObject myDoc = coll.findOne();
System.out.println(myDoc);
//游标遍历
print("游标遍历");
DBCursor cursor = coll.find();
try {
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}
//条件查询
print("条件查询");
BasicDBObject query = new BasicDBObject("i", 71);
cursor = coll.find(query);
try {
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}
//带操作符的条件查询
print("带操作符的条件查询");
query = new BasicDBObject("i", new BasicDBObject("$gt", 20).
append("$lte", 30));
cursor = coll.find(query);
try {
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}
//创建索引
coll.createIndex(new BasicDBObject("i", 1)); // create index on "i", ascending---ascending (1) or descending (-1)
//打印索引信息
print("打印索引信息");
List<DBObject> list = coll.getIndexInfo();
for (DBObject o : list) {
System.out.println(o);
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
static void print(String out){
System.out.println(out);
}
}