import java.util.*;
import net.sf.json.JSONObject;
import java.io.*;
import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;
import com.mongodb.ServerAddress;
import com.mongodb.MongoCredential;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import java.util.Arrays;
-------------------------------------------------------------------------------------
MongoClient mongoClient = null;
try {
//初始化用户名,数据库名,密码
MongoCredential credential = MongoCredential.createCredential("mclogadmin", "mclog", "mclogpass".toCharArray());
// To connect to mongodb server
ServerAddress addr = new ServerAddress("172.17.0.13", 17017);
//auth 连接
mongoClient = new MongoClient(addr,Arrays.asList(credential));
//非auth连接
// mongoClient = new MongoClient( "172.17.0.16" , 17017 );
// Now connect to your databases
@SuppressWarnings("deprecation")
DB db = mongoClient.getDB(dbname);
-------------------------------------------------------------------------------------
MongoClient mongoClient = null;
try{
MongoCredential credential = MongoCredential.createCredential("user", "db", "pass".toCharArray());
// To connect to mongodb server
ServerAddress addr = new ServerAddress("172.17.0.16", 27017);
mongoClient = new MongoClient(addr,Arrays.asList(credential));
// mongoClient = new MongoClient( "172.17.0.16" , 27017 );
// Now connect to your databases
@SuppressWarnings("deprecation")
DB db = mongoClient.getDB(dbname);
DBCollection getCollection=db.getCollection(collectionname);
getCollection.insert((DBObject)com.mongodb.util.JSON.parse(inputjson));
// System.out.println("insert into " + collectionname + " with " + clickid );
//System.out.println("\n insert into " + collectionname + " with " + inputjson );
//mongoClient.close();
} catch(Exception e) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
finally{
if(mongoClient!=null) {
mongoClient.close();
}
}
注意: 在jdk7,eclipse中, mongoClient = new MongoClient(addr,Arrays.asList(credential)); 报错The method asList(T[]) in the type Arrays is not applicable for the arguments
例如,https://stackoverflow.com/questions/43341819/the-method-aslistt-in-the-type-arrays-is-not-applicable-for-the-arguments-i
When I tried to create a list as follow
List l = Arrays.asList(1,2);
I got this error :
The method asList(T[]) in the type Arrays is not applicable for the
arguments (int, int).
最后,eclipse中修改代码为如下:
MongoCredential credential = MongoCredential.createCredential(user,"mclog", pass.toCharArray());
List credentials = new ArrayList();
credentials.add(credential);