日期:2014-05-16 浏览次数:20464 次
<dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>2.11.0</version> </dependency>
import java.net.UnknownHostException; import java.util.Date; import java.util.List; import java.util.Set; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.MongoClient; import com.mongodb.MongoException; public class MongoDBExample { public static void main(String[] args) { try { // 1. 连接到MongoDB服务器 MongoClient mongo = new MongoClient("localhost", 27017); // 2. 获取数据库 // 如果指定的数据库[yourdb]不存在,MongoDB将会新建一个数据库 DB db = mongo.getDB("yourdb"); //显示所有数据库 List<String> dbs = mongo.getDatabaseNames(); for(String database: dbs){ System.out.println("db: "+database); } // 3. 获取一个表 // 如果表不存在,MongoDB将会新建一个 DBCollection table = db.getCollection("users"); //显示选择的数据库中所有表 Set<String> tables = db.getCollectionNames(); for(String coll : tables){ System.out.println("table: "+coll); } // 新增一条记录 BasicDBObject document = new BasicDBObject(); document.put("username", "yourname"); document.put("password", "123456"); document.put("age", 22); document.put("createdDate", new Date()); table.insert(document); // 查找并显示一条记录 BasicDBObject searchQuery = new BasicDBObject(); searchQuery.put("username", "yourname"); DBCursor cursor = table.find(searchQuery); while (cursor.hasNext()) { System.out.println(cursor.next()); } //更新一条记录 BasicDBObject query = new BasicDBObject(); query.put("username", "yourname"); BasicDBObject newDocument = new BasicDBObject(); newDocument.put("username", "yourname-update"); BasicDBObject updateObj = new BasicDBObject(); updateObj.put("$set", newDocument); table.update(query, updateObj); //查找更新后的记录 BasicDBObject searchQuery2 = new BasicDBObject().append("username", "yourname-update"); DBCursor cursor2 = table.find(searchQuery2); while (cursor2.hasNext()) { System.out.println(cursor2.next()); } System.out.println("End"); } catch (UnknownHostException e) { e.printStackTrace(); } catch (MongoException e) { e.printStackTrace(); } } }