我知道如何将数据放入集合中,但如何将它们添加到子数据中,如下面的示例所示?

Jar文件:


  bson-3.4.2.jar,
  mongodb-driver-3.4.2.jar,
  mongodb-driver-async-3.4.2.jar,
  mongodb-driver-core-3.4.2.jar


Java文件:

     MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
     DB db = mongoClient.getDB( "test" );
     System.out.println("Connect to database successfully");

     boolean auth = db.authenticate(myUserName, myPassword);
     System.out.println("Authentication: "+auth);
     DBCollection coll = db.getCollection("mycol");
     System.out.println("Collection mycol selected successfully");

     BasicDBObject doc = new BasicDBObject("title", "MongoDB").
        append("description", "database").
        append("likes", 100).
        append("url", "http://www.instagram.com/").
        append("by", "users");

     coll.insert(doc);


MongoDB:

{
   "_id" : "test",
   "status" : 2,
   "time" : null,
   "instagram" :{
         "description" : "database",
         "likes" : 100,
         "url" : "http://www.instagram.com/",
         "by", "users"
   },
   "batchid" : 15000234
}

最佳答案

将您的代码更新到下面。根据需要添加其余的子数据字段。

BasicDBObject doc = new BasicDBObject("title", "MongoDB").
            append("description", "database").
            append("likes", 100).
            append("url", "http://www.instagram.com/").
            append("by", "users").
            append("instagram", new BasicDBObject("description","database").append("likes", "likes"));


尝试使用较新的api类。 BasicDBObjectDBCollectionDB是旧的2.x类。

就像是。

MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
MongoDatabase db = mongoClient.getDatabase("test");
System.out.println("Connect to database successfully");

boolean auth = db.authenticate(myUserName, myPassword);
System.out.println("Authentication: "+auth);
MongoCollection<Document> coll = database.getCollection("mycol");
System.out.println("Collection mycol selected successfully");

Document doc = new Document("title", "MongoDB").
            append("description", "database").
            append("likes", 100).
            append("url", "http://www.instagram.com/").
            append("by", "users").
            append("instagram", new Document("description","database").append("likes", "likes"));


coll.insertOne(doc);

关于java - 如何在MongoDb中将数据插入子数据?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42361984/

10-09 17:45
查看更多