2011-07-24 8 views
5

からのデータを保存します。私のようなマップに部署AとBのデータを持っているしかしMongoのデータベースは、私が働く以下のコードを持っている地図

if (aDBCursor.hasNext()) { 
    DBObject aDbObject = aDBCursor.next(); 
    aDbObject.put("title", "Test Title"); 
    ArrayList<DBObject> department = new ArrayList<DBObject>(); 

    DBObject nested1 = new BasicDBObject(); 
    nested1.put("name", "Department A"); 
    nested1.put("id", 1); 
    department.add(nested1); 

    DBObject nested2 = new BasicDBObject(); 
    nested2.put("name", "Department B"); 
    nested2.put("id", 2); 
    department.add(nested2); 

    aDbObject.put("department", department); 
    collection.save(aDbObject); 
} 

Map<Object,Object> map = new HashMap<Object,Object>(); 
map.put("1", "Department A"); 
map.put("2", "Department B"); 

何最善だろう/このデータを保存するのが最も簡単な方法ですか?マップをmongo DBに直接挿入する方法はありますか?それとも、地図上をループする必要がありますか?すでにそのようにデータベースから取得されマップに入る

データ:

String[] values = req.getParameterValues("departments"); 
Map<Object,Object> map = new HashMap<Object,Object>(); 

DBCollection collection = database.getCollection("Departments"); 
BasicDBObject query = new BasicDBObject(); 
query.put("id", new BasicDBObject("$in", values)); 
DBCursor cursor = collection.find(query); 

も良いでしょうが、私はただのDBcursorが戻ってデータベースにオブジェクト置くことができます。

アイデア?

ありがとうございました!

答えて

5

ネイティブJava型(intfloatStringDateMap,など)が自動的に右BSONタイプに符号化されますので、あなたはまっすぐMongoのコレクションにMapを入れてBasicDBObjectを使用することができます。

// you probably want to be more specific with your generics than Object! 
Map<Object,Object> map = new HashMap<Object,Object>(); 
map.put("1", "Department A"); 
map.put("2", "Department B"); 
collection.insert(new BasicDBObject(map)); 

しかし、Mapには実際に必要な構造がないようですので、希望の構造にある種のマッピングが必要です。 Javaドライバに組み込まれている基本的なマッピングを使用するか(適切なトラックにはBasicDBObject.putを呼び出し、hereはいくつかのアイデアです)、拡張マッピングにはMorphiaのようなものを使用してください。

0

What would the best/easiest way be to save this data? Is there a way to put the map straight into the mongo DB? Or would I have to loop over the map? Mapはコンストラクタ自体を介してBasicDBObjectに直接追加することができます。これは反復処理なしで直接dbに挿入できます。

Would be even better is I could just put the DBCursor object back into the database. 

はのDBcursorはイテレータを実装し、それが

2

[OK]をみんなを反復することなく、DBに戻すことができない、私が働いてそれを得ました。

String[] values = req.getParameterValues("departments"); 
Map<Object,Object> map = new HashMap<Object,Object>(); 

DBCollection collection = database.getCollection("Departments"); 
BasicDBObject query = new BasicDBObject(); 
query.put("id", new BasicDBObject("$in", values)); 
DBCursor cursor = collection.find(query); 



if(aDBCursor.hasNext()){ 
     DBObject aDbObject=aDBCursor.next(); 
     aDbObject.put("title", "Test Title"); 
     aDbObject.put("department", cursor); 
     collection.save(aDbObject); 
    } 

同様に簡単です!

ご返信いただきありがとうございます。

関連する問題