我的文档是这样的:
{
{
mlsId: 'RTC749',
firstName: 'Tommy',
lastName: 'Davidson',
officeMlsId: 'RTC2421',
officeName: 'John Jones Real Estate LLC',
slug: 'tommy-davidson',
serviceAreas: [
{
name: 'Nashville',
slug: 'nashville',
type: 'city',
totalClosedSales: 3
},
{
name: 'Franklin',
slug: 'franklin',
type: 'city',
totalClosedSales: 7
}
},
{
id: 'RTC7280',
firstName: 'Jack',
lastName: 'Miller',
slug: 'jack-miller',
serviceAreas: [
{
name: 'Nashville',
slug: 'nashville',
type: 'city',
totalClosedSales: 4
},
{
name: 'Franklin',
slug: 'franklin',
type: 'city',
totalClosedSales: 10
}
]
},
}
根据子文档中的 slug 查找文档的查询如下所示:
const localAgents = await Agent.find(
{
'serviceAreas.slug': locationSlug,
},
'-_id -__v'
)
.sort({ 'serviceAreas.totalClosedSales': -1 })
请注意,我想通过位置标签查找代理并使用 totalClosedSales
对结果进行排序,但我无法让它工作。所以期望的结果看起来像这样:
{
{
id: 'RTC7280',
firstName: 'Jack',
lastName: 'Miller',
slug: 'jack-miller',
serviceAreas: [
{
name: 'Franklin',
slug: 'franklin',
type: 'city',
totalClosedSales: 10
},
{
name: 'Nashville',
slug: 'nashville',
type: 'city',
totalClosedSales: 4
}
]
},
{
mlsId: 'RTC749',
firstName: 'Tommy',
lastName: 'Davidson',
officeMlsId: 'RTC2421',
officeName: 'John Jones Real Estate LLC',
slug: 'tommy-davidson',
serviceAreas: [
{
name: 'Nashville',
slug: 'nashville',
type: 'city',
totalClosedSales: 3
},
{
name: 'Franklin',
slug: 'franklin',
type: 'city',
totalClosedSales: 7
}
]
},
}
最佳答案
我们不能直接对数组进行排序,但是聚合可以帮助它
$unwind
帮助解构数组$sort
帮助按您的意愿排序$group
帮助重新分组解构数组
下面给出了Mongo脚本
db.collection.aggregate([
{
"$match": {
"serviceAreas.slug": "nashville"
}
},
{
$unwind: "$serviceAreas"
},
{
$sort: {
"serviceAreas.totalClosedSales": -1
}
},
{
$addFields: {
total: "$serviceAreas.totalClosedSales"
}
},
{
$sort: {
total: -1
}
},
{
$group: {
_id: "$_id",
mlsId: {
$first: "$mlsId"
},
firstName: {
$first: "$firstName"
},
lastName: {
$first: "$lastName"
},
slug: {
$first: "$slug"
},
serviceAreas: {
$push: "$serviceAreas"
}
}
}
])
关于mongodb - 基于数组 Mongoose/Mongodb 中嵌套子文档的 desc 值对查询结果进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64673548/