环境简介:
java版本:1.8
mongoDB版本:3.4.5
Linux机器ip:192.168.61.186
下载支持jar:地址是:
https://oss.sonatype.org/content/repositories/releases/org/mongodb/mongo-java-driver/3.4.3/
最好把源码也下载下来
创建java工程
查看源码:
知道mongoDB服务器的ip和端口即可连接:
package com.adtec.mongodb;
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;
/**
*
* @author 浪丶荡
*
*/
public class MongoDBUtils {
public static void main(String[] args) {
//连接到 mongodb 服务
String host = "192.168.61.186";
int port = 27017;
@SuppressWarnings("resource")
MongoClient mongoClient = new MongoClient(host,port);
// 连接到数据库
String databaseName = "test";
MongoDatabase database = mongoClient.getDatabase(databaseName);
//选择集合(类似选择表)
String collectionName = "country";
MongoCollection<Document> collection = database.getCollection(collectionName);
//获取迭代器FindIterable<Document>
FindIterable<Document> findIterable = collection.find();
//获取游标MongoCursor<Document>
MongoCursor<Document> mongoCursor = findIterable.iterator();
//通过游标遍历检索出的文档集合
while(mongoCursor.hasNext()){
System.out.println(mongoCursor.next());
}
}
}