【发布时间】:2018-12-25 06:15:03
【问题描述】:
我有三个集合 - 文章、类别和用户。每篇文章都可以有作者和副作者,我想列出 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 } }
]
【问题讨论】:
-
没有
$sort这个管道输出什么?
标签: mongodb sorting mongoose aggregation-framework project