2017-01-02 97 views
1

搜索多個值,我有以下集合:嵌套數組中

{ 
_id: 1, 
docs: [{ 
      name: file1, 
      labels: [label1, label2, label3, label4] 
     },{ 
      name: file2, 
      labels: [label3, label4] 
     },{ 
      name: file3, 
      labels: [label1, label3, label4] 
     }] 
} 

當標籤用戶搜索,我需要得到所有具有這些標籤的文檔。

因此,如果用戶搜索「label1」和「label3」,我需要獲得「file1」和「file3」。目前我有以下代碼:

var collection = db.collection(req.user.username); 

    collection.aggregate([ 
     // Unwind each array 
     { "$unwind": "$docs" }, 
     { "$unwind": "$docs.labels" }, 

     // Filter just the matching elements 
     { 
      "$match": { 
       "docs.labels": { "$all": ["label1", "label3"] } 
      } 
     } 
    ]).toArray(function (err, items) { 
     res.send(items); 
    }); 

這工作正常,如果我只搜索「label1」或「label3」,但不是兩個在一起。你能幫我解決這個問題嗎,因爲我還沒有找到一個適合自己的答案。

+1

你的mongod版本是什麼? – styvane

+0

爲什麼你沒有使用'mongoose'模塊? –

+0

@Styvane my mongo是3.2.10版本 – Mathias

回答

1

您可以在$project階段通過$filter高效地完成此項工作。

let inputLabels = ["label1", "label3"]; 

collection.aggregate([ 
    { "$match": { "docs.labels": { "$all": inputLabels }}}, 
    { "$project": { 
     "docs": { 
      "$filter": { 
       "input": "$docs", 
       "as": "doc", 
       "cond": { "$setIsSubset": [ inputLabels, "$$doc.labels" ] } 
      } 
     } 
    }} 
])]).toArray(function (err, items) { 
     res.send(items); 
    }); 
+0

非常感謝!我自己嘗試使用'$ project'和'$ filter',但由於沒有完全理解它,我無法得到想要的結果。 – Mathias