gpt4 book ai didi

MongoDB多级$lookup排序不起作用

转载 作者:行者123 更新时间:2023-12-02 21:38:09 24 4
gpt4 key购买 nike

多级 $lookup 排序在聚合中不起作用。

排序仅适用于国家/地区、州名称。尝试对城市应用排序,但国家/地区排序会覆盖城市排序。

Query2 正在工作,但我不想在查找管道内对集合进行排序。

有没有办法实现Query1中的所有级别的排序(国家,州,城市)

查询1(不起作用):

Country.aggregate([
{
$lookup:{
from: 'states',
localField:'_id',
foreignField:'countryId',
as:'states'
}
},
{
$unwind: {
path: "$states",
preserveNullAndEmptyArrays: true
}
},
{
$sort: {
'states.name': 1
}
},
{
$lookup:{
from: 'cities',
localField:'states._id',
foreignField:'stateId',
as:'states.cities'
}
},
{
$sort: {
'states.cities.name': 1
}
},
{
$group: {
_id: {
_id: '$_id',
name: '$name'
},
states: {
$push: '$states'
}
}
},
{
$project: {
_id: '$_id._id',
name: '$_id.name',
states: 1
}
},
{
$sort: {
name: 1
}
}
])

查询2(工作):执行时间比 Query1 高 8 倍。

[
{
$lookup : {
from : 'states',
let: { 'countryId': '$_id' },
pipeline: [
{
$match: {
$expr:
{
$eq: ['$countryId', '$$countryId']
}
}
},
{
$sort : {
name : -1
}
}
],
as : 'states'
}
},
{
$unwind: {
path: '$states',
preserveNullAndEmptyArrays: true
}
},
{
$lookup : {
from : 'cities',
let: { 'stateId': '$states._id' },
pipeline: [
{
$match: {
$expr:
{
$eq: ['$stateId', '$$stateId']
}
}
},
{
$sort : {
name : -1
}
}
],
as : 'states.cities'
}
},
{
$group: {
_id: {
_id: '$_id',
name: '$name'
},
states: {
$push: '$states'
}
}
},
{
$project: {
_id: '$_id._id',
name: '$_id.name',
states: 1
}
}
]

最佳答案

在较新的$lookup中您不需要使用 $unwind 的语法连接嵌套字段。您可以轻松使用$lookup在管道内部加入多个级别。

[
{ "$lookup": {
"from": "states",
"let": { "countryId": "$_id" },
"pipeline": [
{ "$match": { "$expr": { "$eq": ["$countryId", "$$countryId"] }}},
{ "$lookup": {
"from": "cities",
"let": { "stateId": "$_id" },
"pipeline": [
{ "$match": { "$expr": { "$eq": ["$stateId", "$$stateId"] }}},
{ "$sort": { "name": -1 }}
],
"as": "cities"
}},
{ "$sort": { "name": -1 }}
],
"as": "states"
}}
]

关于MongoDB多级$lookup排序不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57240061/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com