2017-01-02 138 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