【问题标题】:MongoDB Aggregation: Priorization of matches?MongoDB聚合:匹配的优先级?
【发布时间】: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


    【解决方案1】:

    可能可以使用$project 运算符在一定程度上实现该效果,该运算符允许您动态添加新字段,然后您可以使用这些字段进行排序,但这不会是非常简单。见:

    Mongo 不支持为您完成所有这些的排序。

    实际上,在这种情况下,通常会在您自己的代码中获取字段匹配和排序/过滤的数据,或者获取两个请求 - 一个用于第一个字段匹配,一个用于第二个字段匹配,将它们合并在一起。这并不像看起来那样浪费,性能影响通常无法衡量,但您必须自己测试自己的代码、数据和使用情况。

    【讨论】:

    • 感谢您的详细解答。我解决了类似于您的第二个建议的问题。首先按名称查询,检查答案的长度,如果它不包含足够的项目按类别查询并将这些项目附加到整体响应中。
    猜你喜欢
    • 1970-01-01
    • 2020-07-19
    • 2010-09-28
    • 2020-06-13
    • 2021-04-06
    • 1970-01-01
    • 1970-01-01
    • 2020-06-29
    • 2019-01-24
    相关资源
    最近更新 更多