填充 $lookup 中的特定字段 [英] Populate specific fields in $lookup
问题描述
我正在使用聚合来分组和填充结果,如下所示:
I am using aggregate to group and populate the result like below:
{
"$group": {
"_id": "$userId",
"projectId": { "$push": "$projectId" }
}
},
{
"$lookup": {
"from": "users",
"localField": "_id",
"foreignField": "_id",
"as": "user"
}
},
{ $unwind:"$user" },
{
"$lookup": {
"from": "projects",
"localField": "projectId",
"foreignField": "_id",
"as": "projects"
}
}
但我想从该结果中填充特定字段为此我尝试了$project,但是它将 projectId 组合到一个数组中,将 projectName 组合到另一个数组中.下面是我的结果 json:
But i want to populate specific fields from that result For this I tried $project, But it combining projectId into one array and projectName into another array.Below is my result json:
[
{
"_id": "5c0a29e597e71a0d28b910aa",
"projectId": [
"5c0a2a8897e71a0d28b910ac",
"5c0a4083753a321c6c4ee024"
],
"user": {
"_id": "5c0a29e597e71a0d28b910aa",
"firstName": "Amit"
"lastName": "kumar",
"type": "developer",
"status": "active"
},
"projects": [
{
"_id": "5c0a2a8897e71a0d28b910ac",
"skypeId": "",
"projectName": "LN-PM",
"status": "ongoing",
"assignId": "5c0a2a0a97e71a0d28b910ab"
},
{
"_id": "5c0a4083753a321c6c4ee024",
"skypeId": "",
"status": "pending",
"assignId": "5c0a2a0a97e71a0d28b910ab"
}
]
}
]
现在我想从 user 字段和 "projectName and _id" 字段中获取唯一的 "firstName and _id" 字段strong>项目字段
Now i want to get the only "firstName and _id" field from user field and "projectName and _id" field from the projects field
推荐答案
mongodb 3.6及以上可以使用下面的聚合
You can use below aggregation with mongodb 3.6 and above
使用较新的 $lookup
语法你可以使用 $project
ion#lookup-multiple-joins" rel="nofollow noreferrer">$lookup
管道
With the newer $lookup
syntax you can use $project
ion inside the $lookup
pipeline
db.collection.aggregate([
{ "$group": {
"_id": "$userId",
"projectId": { "$push": "$projectId" }
}},
{ "$lookup": {
"from": "users",
"let": { "userId": "$_id" },
"pipeline": [
{ "$match": { "$expr": { "$eq": [ "$_id", "$$userId" ] }}},
{ "$project": { "firstName": 1 }}
],
"as": "user"
}},
{ "$unwind": "$user" },
{ "$lookup": {
"from": "projects",
"let": { "projectId": "$projectId" },
"pipeline": [
{ "$match": { "$expr": { "$in": [ "$_id", "$$projectId" ] }}},
{ "$project": { "projectName": 1 }}
],
"as": "projects"
}}
])
这篇关于填充 $lookup 中的特定字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!