Reputation: 31
I want to update a json data that comes from API and update it in MongoDB, but i don't have an idea how to do. I need to update instead of Insert, but don't know is it possible to update array. Here is my code:
public static void getObject() throws Exception {
String api = "http://welcometoastana.kz/api/v1/places/events";
String dbURI =
"mongodb://api:[email protected]:27017/smartdata";
MongoClient mongo = new MongoClient(new MongoClientURI(dbURI));
MongoDatabase db = mongo.getDatabase("smartdata");
URL url = new URL(api);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Accept-Language", "en");
Scanner scan = new Scanner(url.openStream());
String str = new String();
while (scan.hasNext())
str += scan.nextLine();
scan.close();
//getting real json arrays
JSONObject obje1 = new JSONObject(str);
JSONArray jArray = obje1.getJSONArray("places");
for (int i = 0; i<jArray.length(); i++) {
JSONObject object3 = jArray.getJSONObject(i);
int id = object3.getInt("id");
String slug = object3.getString("slug");
String name = object3.getString("name");
String summary = object3.getString("summary");
String phone = object3.getString("phone");
String address = object3.getString("address");
String description = object3.getString("description");
String url1 = object3.getString("url");
String url_ticketon = object3.getString("url_ticketon");
System.out.println("id = "+id+"\n slug = "+slug+"\n name = "+name+
"\n summary = "+summary+"\n phone = "+phone+
"\n address = "+address+"\n description = "+description+"\n"+
"\n url = "+url1+"\n url_ticketon = "+url_ticketon);
List<Document> writes = new ArrayList<>();
MongoCollection<Document> sobt = db.getCollection("sobt");
Document d2 = new Document("id", id);
d2.append("slug", slug);
d2.append("name", name);
d2.append("summary", summary);
writes.add(d2);
sobt.insertMany(writes);
Upvotes: 2
Views: 5178
Reputation: 185
Document filter = new Document("id", id);
Document content = new Document();
contend.append("slug", slug);
content.append("name", name);
content.append("summary", summary);
Document update = new Document("$set", content);
sobt.update(filter, update);
Upvotes: 4