使用mongodb,我试图在明确的类别列表中找到name
匹配用户输入的条目,或者同一列表中的类别与用户输入匹配的条目。
我想过滤集合只显示这些类别["major olympian", "twelve titan", "primordial deity"]
用户可以从其中一个类别中搜索name
,也可以搜索类别以显示与用户输入匹配的类别中的所有条目,并在数组中提及
在收集过滤之前,这有效,但现在我只想要过滤类别数组的结果:
let _query = {
'$or': [
{
"name": {
"$regex": search,
"$options": "i"
}
},
{
"category": {
"$regex": search,
"$options": "i"
}
}
]
};
以下是具体示例:
如果用户输入an
,则会返回name
包含an
类["major olympian", "twelve titan", "primordial deity"]
的所有条目以及major olympian
和twelve titan
中的所有条目{1}}
以下是我的收藏样本,其中一个类别creature
从不显示:
{
"name": "Zeus",
"greekName": "Ζεύς, Zeus",
"romanName": "Jupiter",
"description": "King of the gods, ruler of Mount Olympus, and god of the sky, weather, thunder, lightning, law, order, and justice. He is the youngest son of Cronus and Rhea. He overthrew Cronus and gained the sovereignty of heaven for himself. In art he is depicted as a regal, mature man with a sturdy figure and dark beard. His usual attributes are the royal scepter and the lightning bolt. His sacred animals include the eagle and the bull. His Roman counterpart is Jupiter, also known as Jove.",
"category": "major olympian"
},
{
"name": "Ophiogenean dragon",
"greekName": "",
"romanName": "",
"description": "a dragon that guarded Artemis' sacred grove in Mysia.",
"category": "creature",
},
{
"greekName": "Ἀχλύς (Akhlýs)",
"name": "Achlys",
"description": "The goddess of poisons and the \"Death-Mist\", and personification of misery and sadness. Said to have existed before Chaos itself.",
"category": "primordial deity",
"romanName": ""
}
答案 0 :(得分:1)
你可以尝试这样的事情。
const _query = {
category: {
$in: TEMP_CATEGORIES
},
'$or': [{
"name": {
"$regex": search,
"$options": "i"
}
}, {
"category": {
"$regex": search,
"$options": "i"
}
}]
};
答案 1 :(得分:0)
感谢@Veeram评论,我设法让它发挥作用。
const TEMP_CATEGORIES = ["major olympian", "twelve titan", "primordial deity"];
const _query = {
'$or': [
{
$and: [
{
"name": {
"$regex": search,
"$options": "i"
}
},
{
category: { $in: TEMP_CATEGORIES }
}
],
},
{
$and: [
{
"category": {
"$regex": search,
"$options": "i"
}
},
{
category: { $in: TEMP_CATEGORIES }
}
],
},
]
};
Greek
.find(_query)
.sort({ name: 1 })
.exec((err, greeks) => {
if (err) {
console.warn(err);
reject(err)
} else {
resolve(greeks);
}
});
});
我不知道这是不是正确的方法,但似乎有效。(我想我应该对它进行单元测试......)