2016-09-29 108 views
3

我有這個文件的結構:獲取MongoDB的陣列子集

{ 
    Id: "id_value", 
    Elements:[ 
       { 
        InnerId: "inner_id_value1", 
        Value: "apple" 
       }, 
       { 
        InnerId: "inner_id_value2", 
        Value: "pear" 
       }, 
       { 
        InnerId: "inner_id_value3", 
        Value: "banana" 
       } 
      ] 
} 

什麼,我需要做的是創造出在輸入端接收陣列(例如["apple","banana","coconut"]),並返回到我的查詢:

{ 
    Id: "id_value", 
    Elements:[ 
       { 
        InnerId: "inner_id_value1", 
        Value: "apple" 
       }, 
       { 
        InnerId: "inner_id_value3", 
        Value: "banana" 
       } 
      ] 
} 

是否有可能在Mongo中用單個查詢來做到這一點?

+0

什麼是你的MongoDB版本的時間? – styvane

+0

@Styvane版本3.2 – Marco

回答

3

您只需要$filter該數組,並且只保留那些是輸入數組子集的子文檔。請注意,這裏是一個元素數組,其中元素是嵌入字段value

let fruits = ["apple","banana","coconut"]; 

db.collection.aggregate([ 
    { "$project": { 
     "Element": { 
      "$filter": { 
       "input": "$Element", 
       "as": "el", 
       "cond": { 
        "$setIsSubset": [ [ "$$el.Value" ], fruits ] 
       } 
      } 
     } 
    }} 
]) 

從MongoDB的3.4啓動*您可以在$project階段使用$in操作。

db.collection.aggregate([ 
    { "$project": { 
     "Element": { 
      "$filter": { 
       "input": "$Element", 
       "as": "el", 
       "cond": { 
        "$in": [ "$$el.Value", fruits ] 
       } 
      } 
     } 
    }} 
]) 

的MongoDB *未發行版本在寫這篇文章

+0

$ setIsSubset對我來說是新的。謝謝! 只是對空集方案感興趣,因爲它是每個集合的子集 - 如果$$ el.Value對於文檔是空的,那麼不會包含在此查詢結果中? – sudheeshix

+0

不,它不會被包括在內。 – styvane