本实例是提供给刚开始用java连接MongoDB的人,奔着简单,清晰,快速上手的原则,特发此实例
数据库内容是
Collections 内容是
username 内容是
连接代码
package com.mongo;import java.net.UnknownHostException;import java.util.Set;import com.mongodb.DB;import com.mongodb.DBCollection;import com.mongodb.DBCursor;import com.mongodb.DBObject;import com.mongodb.Mongo;public class Test { public void getConnMongodb(){ try { Mongo mongo=new Mongo(); DB db= mongo.getDB("login");// name of databases Setcols = db.getCollectionNames(); for (String s : cols) { System.out.println(s); } DBCollection collection=db.getCollection("username");//name of collection DBObject dbobj=collection.findOne(); //findone()=find().limit(1) System.out.println(dbobj); DBCursor cursor= collection.find(); while (cursor.hasNext()) { DBObject dbObject = (DBObject) cursor.next(); System.err.println(dbObject); System.err.println(dbObject.get("name")+"|"+dbObject.get("age")); // name and age is the key of documents } } catch (UnknownHostException e) { e.printStackTrace(); } } public static void main(String[] args) { Test test=new Test(); test.getConnMongodb(); }}
后台打印信息是