MongoDB在排序函数中使用字段值
我的MongoDB知识非常紧凑,但在我的MongoDB设置中,我们将翻译保存在一个数组中。问题是我需要根据原始语言代码对标题进行排序。所以我想在sort函数中使用originalLangCode值 因此,如果我想只对NL语言进行排序。我的问题如下:MongoDB在排序函数中使用字段值,mongodb,sorting,indexing,field,Mongodb,Sorting,Indexing,Field,我的MongoDB知识非常紧凑,但在我的MongoDB设置中,我们将翻译保存在一个数组中。问题是我需要根据原始语言代码对标题进行排序。所以我想在sort函数中使用originalLangCode值 因此,如果我想只对NL语言进行排序。我的问题如下: db.getCollection("name").find({}).sort({"translations.NL.title" : 1}); 但我真正想要的是: db.getCollection("name").find({}).sort({"t
db.getCollection("name").find({}).sort({"translations.NL.title" : 1});
但我真正想要的是:
db.getCollection("name").find({}).sort({"translations.originalLangCode.value.title" : 1});
所以伙计们,任何帮助都将不胜感激 将值作为键不是一种好的做法。当您使用值作为键时,很难对它们进行查询,因为在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}
}
]
)
**上述解决方案适用于低于3.3.5的mongodb版本,您应该使用它,因为最新的稳定版本是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}
}
]
)
我已经在本地系统上测试了第一个代码,但还没有检查开关盒 所以你想按“originalLangCode”的值排序,对吗?所有文档中的语言数量有限吗?酷,你帮了我很多!谢谢你给我这样的想法!