MongoDB获取所有字段+按多个字段计算出的值排序 [英] MongoDB get all fields + sort by value computed from multiple fields

查看:1025
本文介绍了MongoDB获取所有字段+按多个字段计算出的值排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从MongoDB的集合中获取文档。单个文档如下所示:

I need to get documents from collection in MongoDB. A single document looks like this:

{
    name    : "John Doe",
    address : "Some cool address",
    value1  : 2,
    value2  : 3,
    value3  : 5
}

我需要检索所有字段并按等于 value1 + value2 + value3 的数字降序排列文档。

I need to retrieve all fields + sort the documents descending by number equal to value1 + value2 + value3.

我发现的唯一解决方案(不完整,因为它不能检索所有字段)看起来像这样:

Only solution I found (incomplete because it doesn't retrieve all fields) looks like this:

db.someCollection.aggregate(
    {
        $project: {
            sum: { $add: [ "$value1", "$value2", "$value3" ] }
        },
        $sort: {
            sum: -1
        }
    }
)

就像我说的那样,这仅返回 sum 字段,这不是我想要的。

Like I said, this returns only sum field which is not what I want.

编辑:现实中文档也较大,所以我不想使用伪解决方案,例如

Also the document is a bit larger in reality so I don't want to use pseudo-solution like

$project: {
    name:    1,
    address: 1,
    ...
}

ie我想要一些通用的可重用解决方案,而不是针对特定情况的解决方案

i.e. I'd like some universal reusable solution, not the case-specific one

推荐答案

尝试以下查询:

db.myCollection.aggregate(
{$project: {name : "$name", 
            address : "$address", 
            value1 : "$value1", 
            value2 : "$value2", 
            value3 : "$value3",
            sum : {$add : ["$value1", "$value2", "$value3"]}}},
{$sort: {sum: -1}}
)

据我所知,MongoDB中没有按条件排序之类的选项。另外,默认情况下也没有选项将所有字段添加到项目中。

As far as I know, there is no option like sort by condition in MongoDB. Also there is no option to add all the fields into the the project by default. There was an issue for this but it is not resolved yet.

目前,另一种选择是创建新字段(例如:totalValues)并将总和存储在该字段中。字段以及值字段何时更改。然后,您可以按totalValues排序。

For now, another option would be to create new field (ex : totalValues) and store the sum in that field and when value fields changed. Then you can sort by totalValues.

这篇关于MongoDB获取所有字段+按多个字段计算出的值排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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