JAVA使用MongoDB

JAVA使用MongoDB


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.util.JSON;
public class MongoGBTest {
    public static void main(String[] args) throws Exception {
        Mongo mg = new Mongo();
        // 查询所有的Database
        for (String name : mg.getDatabaseNames()) {
            System.out.println("dbName: " + name);
        }
        DB db = mg.getDB("test");
        // 查询所有的聚集集合
        for (String name : db.getCollectionNames()) {
            System.out.println("collectionName: " + name);
        }
        DBCollection users = db.getCollection("users");
        for (int i = 0; i < 3; i++) {
            DBObject o = new BasicDBObject().append("name", "name" + i).append("age", 20 + i).append("no", i + 10);
            users.insert(o);
        }
        // 查询所有的数据
        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));
    }
}  

你可能感兴趣的:(JAVA使用MongoDB)