如何从Android应用程序插入数据到mongodb?

时间:2016-10-05 05:44:32

标签: android mongodb

我想将我的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();
}

2 个答案:

答案 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();
}

确保您通过mavengradle安装mongo驱动程序,以便您拥有所有瞬态依赖项,因为mongo驱动程序需要bsonmongodb-driver-core

答案 1 :(得分:0)

先生,谢谢你。我正在使用mlab.com并获取连接字符串... import mongo-java-driver-3.4.0-SNAPSHOT和bson 3.3.0。 enter image description here 图片显示连接状态已连接。但不要插入数据库 编辑的代码:

 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();
    }