【发布时间】:2017-08-23 05:32:25
【问题描述】:
我在理解如何按优先级排序我的项目时遇到问题。
我发现这可以通过聚合来实现。假设这是我的收藏:
{
'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",
],
}
如果我的正则表达式是 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 */
}
])
【问题讨论】:
标签: javascript node.js mongodb mongoose aggregation-framework