按elemMatch在MongoDB中排序 [英] Sorting in MongoDB by elemMatch

查看:54
本文介绍了按elemMatch在MongoDB中排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在MongoDB中是否有一种基于$elemMatch的排序方式?例如,我有看起来像这样的文档:

Is there a way of sorting in MongoDB based on an $elemMatch? For example, I have documents which look like this:

{
    'user': ObjectId('fsdfsdf'),
    ...
    'array_of_things': [
        {
            'attribute_1': ObjectId('sdfsdfsd'),
            'attribute_2': ObjectId('sdfsfsdf'),
            'value': 30000
        },
        {
            'attribute_1': ObjectId('dfdfgfdg'),
            'attribute_2': ObjectId('gdfgdfgd'),
            'value': 100
        },
        {
            'attribute_1': ObjectId('mbnmbbmb'),
            'attribute_2': ObjectId('mbnmbnmb'),
            'value': 2000
        },
        ...
    ]
}

我需要能够基于array_of_things字段内的匹配元素来查询此数据(使用$elemMatch足够简单).出现问题是因为我还需要能够按与某个属性匹配的值(升序或降序)进行排序.例如,查询可能是:

I need to be able to query this data based on a matching element inside the array_of_things field (which is simple enough with an $elemMatch). The problem arises because I also need to be able to sort by value (ascending or descending) that match a certain attribute. For example, a query might be:

{
    'user': ObjectId('fsdfsdf'),
    'array_of_things': {
        $elemMatch: {
            'attribute_1': ObjectId('dfdfgfdg'),
            'value': {
                $gt: 1
            }
        }
    }
}

仅对value进行排序(例如,按预期,sort({ 'array_of_things.value': -1 })仅对任何数组元素中的所有值进行排序,而不是首先与attribute_1匹配.

Sorting solely on value (e.g. sort({ 'array_of_things.value': -1 }) predictably only sorts on all values in any array element, not matching attribute_1 first.

有没有办法做到这一点?

Is there a way to do this?

很抱歉,如果这是一个已经提出的问题,但是看完之后我似乎找不到任何解决方案.

Apologies if this is an already-asked question, but I can't seem to find any solution to it after looking.

推荐答案

当前无法使用标准查询语言来实现.您可以使用聚合框架(可能)在性能上有所损失.

This is currently not possible with the standard query language. You can achieve it with the aggregation framework at (potentially) some performance penalty.

这篇关于按elemMatch在MongoDB中排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆