0
我有問題了解如何使用優先級對項目進行排序。MongoDB聚合:匹配的優先級?
我發現這可以通過聚合來實現。假設這是我收集:
{
'title': 'Applepie'
"categories" : [
"Cake",
"Healthy",
],
},
{
'title': 'Chocolatecake'
"categories" : [
"Cake",
"Healthy",
],
},
{
'title': 'Some other Cake without apple in the title but in category'
"categories" : [
"Cake",
"Apple",
],
}
我想實現下面的輸出,如果我正則表達式是蘋果:
{
'title': 'Applepie'
"categories" : [
"Cake",
"Healthy",
],
},
{
'title': 'Some other Cake without apple in the title but in category'
"categories" : [
"Cake",
"Apple",
],
}
這是我迄今爲止基本上只找到比賽到現在爲止:
var regex = new RegExp('abc', 'i');
db.getCollection('items').aggregate([
{ $match: {
$or: [
{ title: { $regex: regex }},
{ categories: { $regex: regex }}
]
}
},
{
/* sort that those with the matching title come first and then those with matching category */
}
])
感謝您的詳細解答。我解決了我的問題,類似於你的第二個建議。首先按名稱查詢,檢查答案的長度,如果它沒有包含足夠的項目按類別查詢並將這些項目追加到整體響應。 – Marco