Mongoose-将数组中的数据搜索/过滤到具有特定项目的另一个数组中 [英] Mongoose- Search/Filter data from array into another array with the specific items
本文介绍了Mongoose-将数组中的数据搜索/过滤到具有特定项目的另一个数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个像 mongoDB 对象
I have an mongoDB object like
{
"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"
}
]
}
有时我只需要使用仅匹配 courseName
和 user
.
Sometime I have to use only match the courseName
and user
only.
另一次我必须使用 courseName
user
和 topics
进行查询其中至少匹配一个主题的主题.我该如何处理这个过程?
Another time I have to query with the courseName
user
and topics
where topics which at least match one topic. How can i handle this process?
当我将输入作为 courseName
、user
和主题 ["b"]
传递时.我在返回输出中取消了 user
和 optionsSet
的选择.我的预期输出将是:
When I pass input as courseName
, user
and topics ["b"]
. I deselected user
and optionsSet
in return output. My expected out put will be :
{
"courseName" : "AI",
"questions" : [
{
"topics" : ["b", "c", "a"],
},
{
"topics" : ["b"],
}
]
}
这可能吗?
推荐答案
可以使用聚合查询,
$match
使用$in
运算符检查您的条件$filter
迭代questions
循环并检查主题是否有任何输入搜索topics
$filter
迭代topics
的循环并搜索topics
$match
to check your condition using$in
operator$filter
to iterate loop ofquestions
and check if topics having any input searchtopics
$filter
to iterate loop oftopics
and search fortopics
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();
这篇关于Mongoose-将数组中的数据搜索/过滤到具有特定项目的另一个数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文