I know how we put datas in the collections but how do we add them in subdatas like in example below?
Jar Files:
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 Files:
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
}
Since you are using Java, take a look at jongo and the "dot notation":
In your case, you could do something like this:
collection.update("{ _id: 'test'}").with("{$set: {"instagram.likes": 2}})
Update your code to below. Add rest of sub data fields as you needed.
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"));
Try using newer api classs. BasicDBObject
, DBCollection
& DB
are old 2.x classes.
Something like.
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.