Mongoose- Search/Filter 数据从一个数组到另一个包含特定项目的数组

Mongoose- Search/Filter data from array into another array with the specific items

我有一个 mongoDB 对象

{   
    "courseName" : "AI",
    "user" : ObjectId("6087dc4c2ba7a828363c9fca"),
    "questions" : [ 
        { 
             "optionsSet" : [ 
                {
                    "value" : "A",
                },
                {
                    "value" : "B",
                }
             ],
            "topics" : ["b", "c", "a"],
            "createdAt" : "2021-07-07T18:41:18.971Z"
        }, 
        {
           "optionsSet" : [ 
                {
                    "value" : "C",
                },
                {
                    "value" : "D",
                }
             ],
            "topics" : ["c"],
            "createdAt" : "2021-08-07T18:41:18.971Z
        },
        {
            "optionsSet" : [ 
                {
                    "value" : "CC",
                },
                {
                    "value" : "DD",
                }
             ],
            "topics" : ["b"],
            "createdAt" : "2021-08-07T18:41:30.971Z"
        }
    ]
}

有时我必须只匹配 courseNameuser

另一次我不得不用 courseName usertopics 查询 其中至少匹配一个主题的主题。我该如何处理这个过程?

当我将输入作为 courseNameuser 和主题 ["b"] 传递时。我在 return 输出中取消选择 useroptionsSet。我的预期输出将是:

{
    "courseName" : "AI",
    "questions" : [ 
        {
            "topics" : ["b", "c", "a"],
        }, 
        {
            "topics" : ["b"],
        }
    ]
}

这可能吗?

可以使用聚合查询,

  • $match 使用 $in 运算符
  • 检查您的情况
  • $filter 迭代 questions 的循环并检查主题是否有任何输入搜索 topics
  • $filter 迭代 topics 的循环并搜索 topics
let p = YourSchema.aggregate();

// courseName
if (req.body.courseName) p.match({ courseName: req.body.courseName });

// user
if (req.body.user) p.match({ user: req.body.user });

// topics
if (req.body.topics) {
  p.match({ "questions.topics": { $in: req.body.topics } });

  p.addFields({
    questions: {
      $filter: {
        input: "$questions",
        cond: {
          $ne: [
            {
              $filter: {
                input: "$$this.topics",
                cond: { $in: ["$$this", req.body.topics] }
              }
            },
            []
          ]
        }
      }
    }
  });
}

let result = await p.exec();

Playground