我想将我的json数据插入到mongo数据库中,我导入mongo Driver v 3.2.2并在mlab.com中创建一个数据库集合,但我无法在数据库中发送数据这样的文档。
这是我的代码:
try {
MongoClientURI uri = new MongoClientURI("mongodb://user:pass@ds041939.mlab.com:41939/vado");
MongoClient client = new MongoClient(uri);
DB db = client.getDB(uri.getDatabase());
DBCollection collection = db.getCollection("salam");
DBObject dbObject = (DBObject) JSON.parse("{'name':'mkyong', 'age':30}");
collection.insert(dbObject);
DBCursor cursorDoc = collection.find();
while (cursorDoc.hasNext()) {
System.out.println(cursorDoc.next());
}
} catch (Exception e) {
e.printStackTrace();
}
答案 0 :(得分:0)
您的代码有点弃用。我调整了它(使用mongo-driver 3.2.2)并对我当地的mongo进行了测试,它运行良好:
try {
MongoClientURI uri = new MongoClientURI("mongodb://localhost:27017/test");
MongoClient client = new MongoClient(uri);
MongoDatabase db = client.getDatabase(uri.getDatabase());
MongoCollection<BasicDBObject> collection = db.getCollection("salam", BasicDBObject.class);
BasicDBObject document = new BasicDBObject();
document.put("name", "mkyong");
document.put("age", 30);
collection.insertOne(document);
MongoCursor iterator = collection.find().iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
} catch (Exception e) {
e.printStackTrace();
}
确保您通过maven
或gradle
安装mongo驱动程序,以便您拥有所有瞬态依赖项,因为mongo驱动程序需要bson
和mongodb-driver-core
。
答案 1 :(得分:0)
try {
MongoClientURI uri = new MongoClientURI("mongodb://va***:******@ds049446.mlab.com:49446/sensingt");
MongoClient client = new MongoClient(uri);
MongoDatabase db = client.getDatabase(uri.getDatabase());
MongoCollection<BasicDBObject> collection = db.getCollection("salam", BasicDBObject.class);
BasicDBObject document = new BasicDBObject();
document.put("name", "mkyong");
document.put("age", 30);
collection.insertOne(document);
MongoCursor iterator = collection.find().iterator();
//System.out.println("Insert successfully");
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
} catch (Exception e) {
e.printStackTrace();
}