2017-06-20 39 views
0

我有這樣的檢索對象數組中的元素查詢在MongoDB中收集

{ 
    "_id" : "toy_in_en_L02B", 
    "modelCode" : "L02B", 
    "path" : "/toy/in/en", 
    "dataPath" : "/toy/in/en/L02B", 
    "basicModelInformation" : { 
     "name" : "News", 
     "startingPrice" : "1234.0" 
    }, 
    "grades" : { 
     "grades" : [ 
      { 
       "key" : "LVL001", 
       "dataPath" : "/toy/in/en/L02B", 
       "name" : "XE P", 
       "price" : "1234.0" 
      }, 
      { 
       "key" : "LVL002", 
       "dataPath" : "/toy/in/en/L02B", 
       "name" : "XE P", 
       "price" : "1234.0" 
      }, 
      { 
       "key" : "LVL003", 
       "dataPath" : "/toy/in/en/L02B", 
       "name" : "XE P", 
       "price" : "1234.0" 
      }, 
      { 
       "key" : "LVL004", 
       "dataPath" : "/toy/in/en/L02B", 
       "name" : "XE P", 
       "price" : "1234.0" 
      } 

     ] 
    } 
} 

一個MongoDB的文件現在我想找回一個完整的文件僅具有一個檔次爲LVL001。但是,當我這樣查詢這個

db.getCollection('models').find({$and: [{"dataPath" : "/nissan/in/en/L02B" }, {"grades.grades" : {$elemMatch: {"key":"LVL002"}}}]}) 

我得到所有的成績。

我已經檢查了線程Retrieve Queried Element但沒有得到它。

我的代碼使用Spring @Query。任何json查詢參數也是有用的。

+0

參考https://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an-object-array-in-mongodb-collection – pynewbie

+0

這是我檢查的第一個線程。這在我的問題中已經提到。但是我沒有得到理想的結果。我想在我的查詢結果中只有一個元素等級(請求)。 – Ashish

+0

你的mongo服務器版本是什麼? – Veeram

回答

1

隨着Mongo 2.2+,你可以使用新的Aggregation Framework

db.getCollection('models').aggregate([ 
    { $unwind : "$grades.grades" }, 
    { $match : {"dataPath": "/nissan/in/en/L02B", 
       "grades.grades.key": "LVL002"}} 
]) 

Unwind解構陣列場從輸入到輸出的每個元素的文檔。使用你發佈的文件作爲例子,放鬆你將有4個文件。然後用match你只需要篩選你想要的文件。

+0

謝謝羅德里戈。當我們必須針對一個年級運行查詢時,它工作正常。但是,當我嘗試運行db.getCollection('models')這樣的多個等級時。aggregate([ {$ unwind:「$ grades.grades」}, {$ match:{「dataPath」:「/ nissan/in/en/L02B「, 」grades.grades.key「:{」in:[「LVL002」,「LVL003」]}}} ])它帶有2個文檔。每個文件包含一個等級。我想要一個可以包含一個文檔下所有成績的模型。 – Ashish

+0

這是我的朋友的另一個問題!放鬆在這種情況下不會有用。 –

+0

任何幫助,將是有用的:)! – Ashish

相關問題