gpt4 book ai didi

mongodb - $addFields where 条件

转载 作者:可可西里 更新时间:2023-11-01 10:36:03 27 4
gpt4 key购买 nike

我想在查找结果中添加额外的字段,但我需要一个条件。每个用户都有一个关系状态(本地字段),应该将其添加到每个用户的查找结果中,但它会将每个“状态”添加到每个用户。

db.getCollection('relationships').aggregate([
{$match: {
user_id: ObjectId("5d3dbe07ea97db13d5b73195")}
},
{
$lookup:
{
from: 'users',
localField: 'relationship.user_id',
foreignField: '_id',
as: 'userss'
}
},
{
$addFields: {
"userss.status": "$relationship.status"
}
},

])

用户模式

{
"_id" : ObjectId("5d3dbe07ea97db13d5b73195"),
"username" : "dipper",
"email" : "test@test.com"
}

关系模式

{
"user_id" : ObjectId("5d3dbe07ea97db13d5b73195"),
"relationship" : [
{
"user_id" : ObjectId("5d3dbe17ea97db13d5b73196"),
"status" : 0
},
{
"user_id" : ObjectId("5d3dbe28ea97db13d5b73197"),
"status" : 1
}
]
}

我需要这样的结果:

{
"_id" : ObjectId("5d3dbe07ea97db13d5b73196"),
"username" : "mabel",
"email" : "test@test.com",
"status": 0

}
{
"_id" : ObjectId("5d3dbe07ea97db13d5b73197"),
"username" : "wendy",
"email" : "test@test.com",
"status": 1

}

最佳答案

你需要$unwind为每个关系获取单个文档:

db.relationships.aggregate([
{
$match: { user_id: ObjectId("5d3dbe07ea97db13d5b73195") }
},
{
$unwind: "$relationship"
},
{
$lookup: {
from: "users",
localField: "relationship.user_id",
foreignField: "_id",
as: "user"
}
},
{
$unwind: "$user"
},
{
$project: {
_id: "$relationship.user_id",
username: "$user.username",
email: "$user.email",
status: "$relationship.status"
}
}
])

关于mongodb - $addFields where 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57301928/

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