2016-03-23 2 views
0

mongoDBドキュメントにペアを挿入しようとしています。このどのように私はこれまでのところ、それをやっている:フィールドへの/からのペアの挿入/取り出し

private static MongoCollection<Document> getCollectionn(String link, String coll){ 
    ... 
} 

public static void main(String[] args) { 
     MongoCollection<Document> fb_users; 
     fb_users = getCollectionn("mongodb://...", "fb_users2"); 
     Document myDoc; 
     BasicDBObject query = new BasicDBObject(); 
     query.put("fbid", "1"); 
     myDoc = fb_users.find(query).first(); 
     int postId=5; 
     int rating=3;     
     fb_users.updateOne(myDoc, 
      new Document("$push", new Document("ratings", java.util.Arrays.asList(rating, postId)))); 

     Object a = myDoc.get("ratings"); 
     ArrayList<Document> b = (ArrayList<Document>) a; 
     System.out.println(b.get(0);//prints [3, 5] 
} 

これは、アレイ文書は二つの実験の後にコレクションに挿入されている方法です。のprintlnで

{ 
    "_id": { 
     "$oid": "56f173b5e4b04eaac6531030" 
    }, 
    "fbid": "1", 
    "ratings": [ 
     [ 
      3, 
      5 
     ], 
     [ 
      3, 
      5 
     ] 
    ] 
} 

私が手 は(文書がすでに存在しています)

がどのように私はnumder 3とseperatly数5を受け取ることができます。結果は[3、5]

私の質問はこれですか?別の方法で文書を挿入する必要がありますか? IAMはmongo javaドライバ3.2.0を使用しています。

答えて

0

私は解決策を見つけました。

Document myDoc; 
    BasicDBObject query = new BasicDBObject(); 
    query.put("fbid", "1"); 
    myDoc = fb_users.find(query).first(); 
    int postId=5; 
    int rating=3; 
    Document listItem = new Document("ratings", new Document(String.valueOf(rating), String.valueOf(postId))); 
    Document updateQuery = new Document("$push", listItem); 
    fb_users.updateOne(myDoc, updateQuery); 
    MongoCursor<Document> curs = fb_users.find(query).iterator(); 
    ArrayList<Document> list = (ArrayList<Document>) myDoc.get("ratings"); 
    Iterator<Document> iterateList = list .iterator(); 
    while(iterateList .hasNext()){ 
     Document pair = iterateList .next(); 
     for(String element : pair.keySet()){ 
      System.out.println(element + " " + pair.get(element)); 
     } 
    } 

とJSON形式であり、このようにする必要があります:ここにある

{ 
    "_id": { 
     "$oid": "56f173b5e4b04eaac6531030" 
    }, 
    "fbid": "1", 
    "ratings": [ 
     { 
      "3": "5" 
     }, 
     { 
      "3": "5" 
     } 
    ] 
} 
関連する問題