在嵌套数组

时间:2017-01-02 19:58:10

标签: node.js mongodb mongodb-query aggregation-framework

我有以下系列:

{
 _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 个答案:

答案 0 :(得分:1)

您可以$filter$project阶段cubes workspace来有效地执行此操作。

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);
    });
相关问题