2017-09-12 14 views
1

ネストされたドキュメントを含むドキュメントがあります。フィルタごとにdata.sms.mobileNumberのようなものを指定できると思いました。しかし、それは動作しません。MongoDBネストされたドキュメントからの読み取り

標準のDocument getStringリクエストを使用して、data.sms.mobileNumberフィールドのデータを読み取るにはどうすればよいですか?

例文献:

{ "_id" : ObjectId("59b850bd81bacd0013d15085"), "data" : { "sms" : { "message" : "Your SMS Code is ABCDEFG", "mobileNumber" : "+447833477560" } }, "id" : "b0a3886d69fc7319dbb4f4cc21a6039b422810cd875956bfd681095aa65f6245" } 

例フィールド取得列要求:

document.getString("data.sms.message") 

答えて

1

'パス' data.sms.messageこのような構造を指す:

+- data 
    | 
    +- sms 
    | 
    +- message 

使用してこれを読むためにあなたがdata文書を読んでいるJavaドライバ、次にsmsサブ文書、次にそのサブ文書のmessage属性。例えば

Document data = collection.find(filter).first(); 
Document sms = (Document) data.get("sms"); 
String message = sms.getString("message"); 

または、ショートカットと同じこと:

String message = collection.find(filter).first() 
    .get("sms", Document.class) 
    .getString("message"); 

アップデート1この質問への答えでは:「私はの配列を持っている場合がありますドキュメント内のドキュメントは、配列内のドキュメントからフィールドを取得する方法はありますか?配列フィールドがdetailsdetailnameageのドキュメントがあるとします。このような何か:

{"employee_id": "1", "details": [{"name":"A","age":"18"}]} 
{"employee_id": "2", "details": [{"name":"B","age":"21"}]} 

あなたがそうのような配列要素を読むことができる:

Document firstElementInArray = collection.find(filter).first() 
     // read the details as an Array 
     .get("details", ArrayList.class) 
     // focus on the first element in the details array 
     .get(0); 

    String name = firstElementInArray.getString("name"); 
+0

ブリリアントありがとう! ドキュメントにドキュメントの配列がある場合、配列内のドキュメントからフィールドを取得するにはどうすればよいですか? –

+0

@NathanEnglish配列要素のアクセスを示す例で答えを更新しました。 – glytching

+0

ありがとう!今、私はそれが完全に意味があることを見ています。 :) –

関連する問題