mongodb - Mongo - 在 $project 之后排序不起作用
问题描述
我有三个集合——文章、类别和用户。每篇文章都可以有作者和副作者,我想列出 currentUser 数据 - 它可以是用户名或昵称,因为用户可以使用两种不同的类型。我对此进行了聚合,它工作正常,但是使用 currentUser 投影列的 $sort 无效 - 是的,它对“某物”进行排序,但不确定是什么,因为“aaa”在开头,然后是“测试”,最后是……“第二次测试”。应该在中间。
我在其中使用 $project 和 $cond 来获取 - 首先是使用当前用户 ID 的特定作者,然后是用户名或昵称。结果还可以,只是排序被破坏了。
顺便提一句。从查找中只获取一条记录而不是使用 $arrayElemAt 是更好的方法吗?
[ { '$match': <MY CONDITIONS> },
{ '$lookup':
{ from: 'categories',
localField: 'category',
foreignField: '_id',
as: 'categories' } },
{ '$lookup':
{ from: 'users',
localField: 'author',
foreignField: '_id',
as: 'author' } },
{ '$lookup':
{ from: 'users',
localField: 'subauthor',
foreignField: '_id',
as: 'subauthor' } },
{ '$project':
{ _id: 1,
name: 1,
status: 1,
updatedAt: 1,
currentUser: {
'$cond': {
'if': { '$eq': [ userId, '$creator'] },
'then': {
'$cond': {
'if': { '$eq': [ '', {'$arrayElemAt': ['$author.username', 0]} ] },
'then': {'$arrayElemAt': ['$author.nickname', 0]},
'else': {'$arrayElemAt': ['$author.username', 0]}
}
},
'else': {
'$cond': {
'if': { '$eq': [ '', {'$arrayElemAt': ['$subauthor.username', 0]} ] },
'then': {'$arrayElemAt': ['$subauthor.nickname', 0]},
'else': {'$arrayElemAt': ['$subauthor.username', 0]}
}
}
}
},
}
},
{ '$sort': { currentUser: 1 } }
]
解决方案
我找到了解决方案 - 这是因为缺少排序规则。添加了 locale en_US / strength = 1 ,现在可以正常工作了。
推荐阅读
- r - 如何使用 R-plot 在图表中显示标签?
- python - 循环遍历 pandas 列名以创建列表
- mysql - 如何从返回多个语句的查询中将数据插入表中?
- c - C 语言 - 打印用户输入字符串中出现频率最高的 3 个字符
- javascript - 使用 vanilla js 禁用/重新启用表单元素 - 无法正常工作
- php - 嵌入 youtube 视频时没有“访问控制允许来源”错误
- java - 如何从字符串数组中获取随机字符串
- sas - SAS - 选择第一次出现唯一 ID 的行(ID 可以在两列中)
- html - bootstrap 4 datetimepicker如何本地化
- flutter - Flutter:尝试从图库或相机中选择图像时,Image_Picker 使应用程序崩溃