Java连接MongoDB示例
示例代码:
package com.zifeiy.snowflake.handle.etl.mongodb;
import java.util.ArrayList;
import java.util.List;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
public class MongodbTest {
public static void main(String[] args) {
MongoClient mongoClient = new MongoClient();
MongoDatabase mongoDatabase = mongoClient.getDatabase("testdb");
System.out.println("connect to database[testdb] successfully");
MongoCollection<Document> collection = mongoDatabase.getCollection("test");
System.out.println("get collection[test] succeed");
// insert
List<Document> documents = new ArrayList<Document>();
documents.add(new Document("name", "zifeiy")
.append("age", 18)
.append("sex", "boy")
.append("weight", "0.1T"));
documents.add(new Document("name", "celina")
.append("age", 20)
.append("sex", "girl")
.append("weight", "50KG"));
collection.insertMany(documents);
System.out.println("documents insert succeed");
// select
FindIterable<Document> findIterable = collection.find();
MongoCursor<Document> mongoCursor = findIterable.iterator();
while (mongoCursor.hasNext()) {
System.out.println(mongoCursor.next());
}
}
}
这里有一篇写的更详细的:http://www.cnblogs.com/wenbronk/p/6385935.html