gpt4 book ai didi

java - 如何用java更新多个文档? MongoDB 3.5 驱动程序

转载 作者:行者123 更新时间:2023-12-02 12:03:51 24 4
gpt4 key购买 nike

我想更新来自 API 的 json 数据并在 MongoDB 中更新它,但我不知道该怎么做。我需要更新而不是插入,但不知道是否可以更新数组。这是我的代码:

public static void getObject() throws Exception {
String api = "http://welcometoastana.kz/api/v1/places/events";
String dbURI =
"mongodb://api:Bottle23Printer@10.10.30.14: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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com