2017-11-01 6 views
0

APIから来るjsonデータを更新してMongoDBで更新したいのですが、どうやってやるのか分かりません。私はInsertの代わりに更新する必要がありますが、配列を更新することは可能かどうかわかりません。ここ は私のコードです:どのようにJavaの多くのドキュメントを更新するには? MongoDB 3.5ドライバ

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); 
+0

あなたが "アップサート" を意味するのではなく、 "挿入しますか"? ['bulkWrite()'](https://docs.mongodb.com/manual/reference/method/db.collection.bulkWrite/)を参照してください。基本的なドキュメントを指していますが、基本的な使い方はすべてのドライバーに当てはまります。同じ基本的な "Bulk API"が 'insertMany()'によって使用されています –

答えて

1
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); 
+0

@Phillipは私のために働いてくれました。 – Marks

+0

もう1つ質問ですが、4つ以上の変数を追加するとコンソールにエラーが表示されます_ **クラスjava.net.URL。** _のコーデックが見つかりません。それを解決するには? – Marks

+0

「4つ以上の変数」には何も関係しません。あなたの変数の1つはjava.net.URLクラスのオブジェクトであり、mongoはそのクラスが何であるかを知らないためです。 'toString()'を使い、変数を文字列としてdbに保存してください。 – Philip

関連する問題