gpt4 book ai didi

node.js - 将数组转换为 $project 中的字符串(聚合)

转载 作者:可可西里 更新时间:2023-11-01 09:32:44 25 4
gpt4 key购买 nike

我使用 $project 操作来指定包含的字段我有这个代码:

[{
'$lookup': {
'from': 'users',
'localField': 'owner',
'foreignField': 'id'
'as': 'user'
}
}, {
'$project': {
'userName': '$user.username',
'userId': '$user.id'
}
}]

我有以下结果:

[
{
"userName": [
"jscode"
],
"userId": [
"5d1888d60c627764aabd8b1e"
]
}
]

我需要将 userIduserName 结果从 array 转换为 string ,如下所示:

[
{
"userName": "jscode" ,
"userId": "5d1888d60c627764aabd8b1e"
}
]

谢谢:)

最佳答案

您可以使用下面的$project阶段

{
"$project": {
"userName": { "$arrayElemAt": ["$user.username", 0] },
"userId": { "$arrayElemAt": ["$user.id", 0] }
}
}

或使用 $unwind

[
{ "$lookup": {
"from": "users",
"localField": "owner",
"foreignField": "id",
"as": "user"
}},
{ "$unwind": "$user" },
{ "$project": {
"userName": "$user.username",
"userId": "$user.id"
}}
]

实际上 $lookup总是以数组的形式返回新字段。因此,要从该数组中选择字段,您需要使用 $unwind或者可以 $arrayElemAt选择第 0 个元素。

关于node.js - 将数组转换为 $project 中的字符串(聚合),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56825102/

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