package org.test;
import java.net.UnknownHostException;
import java.util.Iterator;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.WriteConcern;
public class MongoInstance
{
MongoClient mongoClient = null;
public MongoInstance() throws UnknownHostException
{
// TODO Auto-generated constructor stub
this.mongoClient = new MongoClient();
}
public void test()
{
DB db = mongoClient.getDB("test");
//query all the collections in the db
Iterator it = db.getCollectionNames().iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
// get a collection
DBCollection dbc = db.getCollection("things");
//setting write concern
dbc.setWriteConcern(WriteConcern.JOURNALED);
/* write a document
{
"name" : "MongoDB",
"type" : "database",
"count" : 1,
"info" : {
x : 203,
y : 102
}
}
*/
BasicDBObject doc = new BasicDBObject("_id",1).append("name","MongonDB").append("type", "database").append("count", 1).append("info", new BasicDBObject("x",203).append("y",111));
dbc.save(doc);
DBObject mydoc = dbc.findOne();
System.out.println(mydoc);
System.out.println("--------batch insert--------");
// insert batch
for(int i = 1 ;i < 3;i++)
dbc.insert(new BasicDBObject("i",i));
// get the size of a collection
System.out.println(dbc.getCount());
System.out.println("--------use cursor--------");
// use cursor
DBCursor cur = dbc.find();
while(cur != null && cur.hasNext())
{
System.out.println(cur.next());
}
System.out.println("--------query--------");
//query
BasicDBObject query = new BasicDBObject("i",new BasicDBObject("$gt",0));
cur = dbc.find(query);
while(cur != null && cur.hasNext())
{
System.out.println(cur.next());
}
dbc.remove(query);
}
public static void main(String[] args) throws UnknownHostException
{
MongoInstance mongon = new MongoInstance();
mongon.test();
}
}
需要 到 mongo 官网上 下载 mongo java-driver
this.mongoClient = new MongoClient();
只需要一个 mongoClient 实例即可,他是一个连接池。
MongoClient instance actually represents a pool of connections to the database; you will only need one instance of class MongoClient even with multiple threads