MongoDB 在排序函数中使用字段值

MongoDB use a field value in the sort function

我的 MongoDB 知识非常紧凑,但在我的 MongoDb 设置中,我们将翻译保存在一个数组中。问题是我需要根据原始语言代码对我的标题进行排序。所以我想要排序函数中的originalLangCode值。

所以如果我只想用 NL 语言对它进行排序。我的查询是这样的:

db.getCollection("name").find({}).sort({"translations.NL.title" : 1});

但我真正想要的是:

 db.getCollection("name").find({}).sort({"translations.originalLangCode.value.title" : 1});

one of the records

伙计们,我们将不胜感激!

将值作为键不是一个好习惯。当您使用值作为键时,很难对它们进行查询,因为在 mongodb 中您不能在键字段中传递值。

如果您的语言代码(NL,DE)数量有限,您可以使用以下代码根据原始语言代码对它们进行排序。

db.getCollection('name').aggregate(
   [
      {
         $project: {
            id_: 1,
            corLang: 1,
            corLat: 1,
            translations: 1,
            orignalsort: {
               $concat: [{
                    $cond: [ { $eq: ["$originalLangCode", "NL"] }, "$translations.NL.title", "" ]
                  },{
                    $cond: [ { $eq: ["$originalLangCode", "DE"] }, "$translations.DE.title", "" ]
                  },{
                    $cond: [ { $eq: ["$originalLangCode", "FR"] }, "$translations.FR.title", "" ]
                  }]
            }
         }
      },
      {
        $sort: {orignalsort: 1}
      }
   ]
)

**以上解决方案适用于 mongodb 低于 3.3.5 的版本,您应该使用它,因为最新的稳定版本是 3.2

从即将发布的 3.3.5 版本开始,我们可以使用 $switch 运算符,switch 解决方案如下代码**

db.getCollection('name').aggregate(
   [
      {
         $project: {
            id_: 1,
            corLang: 1,
            corLat: 1,
            translations: 1,
            orignalsort: {
                $switch: {
                    branches: [
                        {
                            case: { $eq: ["$originalLangCode", "NL"] },
                            then: "$translations.NL.title"
                        },  
                        {
                            case: { $eq: ["$originalLangCode", "DE"] },
                            then: "$translations.DE.title"
                        },  
                        {
                            case: { $eq: ["$originalLangCode", "FR"] },
                            then: "$translations.FR.title"
                        },                   
                    ],
                    default: "$translations.NL.title"
                }
            }
         }
      },
      {
        $sort: {orignalsort: 1}
      }
   ]
)

我已经在我的本地系统上测试了第一个代码,但还没有检查 switch case。