我想更新来自 API 的 json 数据并在 MongoDB 中更新它,但我不知道该怎么做。我需要更新而不是插入,但不知道是否可以更新数组。 这是我的代码:
public static void getObject() throws Exception {
String api = "http://welcometoastana.kz/api/v1/places/events";
String dbURI =
"mongodb://api:<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3d7f52494951580f0e6d4f545349584f7d0c0d130c0d130e0d130c09" rel="noreferrer noopener nofollow">[email protected]</a>: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);
最佳答案
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);
关于java - 如何用java更新多个文档? MongoDB 3.5 驱动程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47050671/