2017-03-29 64 views
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 */ 
    } 
]) 

回答

0

可能能夠在一定程度上實現這種效果與$project運算符可以讓您隨時添加新的字段,然後您可以使用它來排序,但這不會很直接。請參閱:

蒙戈不支持排序,將盡一切爲你。

實際上,在這種情況下通常會做的是在您自己的代碼中爲兩個字段匹配和排序/過濾獲取數據,或者獲取兩個請求 - 一個用於第一個字段匹配,一個用於第二個字段匹配並將它們合併在一起。這並不像看起來那麼浪費,性能影響通常無法衡量,但是您必須自己測試一下自己的代碼,數據和使用情況。

+0

感謝您的詳細解答。我解決了我的問題,類似於你的第二個建議。首先按名稱查詢,檢查答案的長度,如果它沒有包含足夠的項目按類別查詢並將這些項目追加到整體響應。 – Marco