在嵌套数组中search多个值

我有以下集合:

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

当用户search标签时,我需要获取所有包含这些标签的文档。

所以如果用户search“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); }); 

这工作正常,如果我只search“label1”或“label3”,但不是在一起。 你能帮我解决这个问题,因为我还没有find一个可以解决问题的答案。

您可以通过在$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); });