首页 > 解决方案 > 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 } }
]

标签: mongodbsortingmongooseaggregation-frameworkproject

解决方案


我找到了解决方案 - 这是因为缺少排序规则。添加了 locale en_US / strength = 1 ,现在可以正常工作了。


推荐阅读