2015-01-05 27 views
0

我有一個包含多個數組元素的文檔。 我想從數組中找到一些特定的值。我想從MongoDB中使用MongoDB獲取數組中的特定數組元素記錄java api

{ 
    "_id" : ObjectId("54a67aa569f2bc6a5865f220"),  
    "language" : "us_english", 
    "country" : "united states", 
    "state" : "texas", 
    "words" : [ 
     { 

      "handle" : "gm", 
      "replacement" : "good morning", 

     }, 
     { 

      "handle" : "ilu", 
      "replacement" : "i love you", 

     } 
    ] 
} 

我想找到的地方replacementhandle is gmlanguage is englishcountry is united statesstate is texas值。

我嘗試了很多解決方案,但我無法從文檔中找到具體的值。

有沒有解決方法?

回答

1

您可以使用聚合操作。

  • $match過濾文件
  • $unwind解構words
  • 重用$match找到replacement

    db.collection.aggregate([{$match : {language : 'us_english', country: 'united states', state: 'texas'}}, {$unwind: '$words'}, {$match: {"words.handle" : "gm"}}]) 
    
    { "_id" : ObjectId("54a67aa569f2bc6a5865f220"), "language" : "us_english", "country" : "united states", "state" : "texas", "words" : { "handle" : "gm", "replacement" : "good morning" } } 
    
+0

你好@Styvane的價值,感謝您的答覆。但我想要使用MongoDB java API的這個解決方案。 – rajesh