2017-03-12 122 views
0

我在數據庫建模這樣一個用例:的MongoDB:檢查是否嵌套數組包含子陣列

name: XYZ 
gradeCards: [{ 
    id: 1234, // id of the report card 
    comments: ['GOOD','NICE','WOW'] 
}, { 
    id: 2345, 
    comments: ['GOOD','NICE TRY'] 
}] 

現在,我有,我想查詢架構如下查詢:

我會給出一個ID和值的列表。 例如:給定列表如下:

[{ 
    id: 1234, 
    comments: ['GOOD','NICE'] 
},{ 
    id: 2345, 
    comments: ['GOOD'] 
}] 

總之ID應當匹配和註釋應該是評論陣列的子陣列,用於該ID,並且還,在指定的所有條件數組應該匹配,所以它應該是所有提供條件的AND條件。

我能找到這個查詢,但它匹配comments數組中的所有元素,我希望該id應該完全匹配,並且註釋應該是子數組。

匹配的評論陣列的所有元素:

db.getCollection('user').find({arr:{ 
    $all: [{ 
     id:1234, 
     comments:['GOOD','NICE','WOW'] 
    },{ 
     id:2345, 
     comments:['GOOD','NICE TRY'] 
    }] 
}}) 

回答

1

你可以嘗試用$all$elemMatch匹配查詢條件。

db.collection.find({ 
    gradeCards: { 
     $all: [{ 
      "$elemMatch": { 
       id: 1234, 
       comments: { 
        $in: ['GOOD', 'NICE'] 
       } 
      } 
     }, { 
      "$elemMatch": { 
       id: 2345, 
       comments: { 
        $in: ['GOOD'] 
       } 
      } 
     }, ] 
    } 
}) 
+0

感謝您的回答,請您解釋爲什麼我們需要$ elemMatch?我得到了$ in的使用。 –

+0

不客氣。 'elemMatch'匹配數組中的至少一個文檔,該文檔具有匹配查詢值的'id'和'comments'以及'$ elemMatch'匹配的'$ all'以在它們各自的查詢條件上匹配這兩個文檔。更多https://docs.mongodb.com/manual/reference/operator/query/elemMatch/ – Veeram

+0

我明白了。感謝您的幫助 –