【问题标题】:How to select only few values from lookup table如何从查找表中仅选择几个值
【发布时间】:2020-06-30 05:14:04
【问题描述】:

我正在尝试使用聚合函数从两个文档中获取数据。我能够做到,但我正在寻找解决方案,如何仅在查找表中应用 $project

下面是我的方法

app.get('/getAllDetailById',(req,res)=>{
    if(db){
        // lookup
        db.collection("points").aggregate(
            [
                { "$addFields": { "enquiry_by": { "$toObjectId": "$enquiry_by" }}},
                { 
                "$lookup" : {
                            from: "user",
                            localField: "enquiry_by",
                            foreignField: "_id",
                            as: "userDetails"
                            }
                },
                { $unwind: "$userDetails"},
             ]
        ).toArray()
        .then(result=>{
            console.log(result[0])
        }).catch(err=>{
                res.send(err)
        })
    }
})

我想要的是从点表和用户表中获取所有字段,我只想要名称和用户名。我使用了 $project 但它只返回在此定义的字段。

{ $project: {"userDetails.name":1, "userDetails.username":1,"_id":0} }

有没有什么方法可以单独为用户表申请$project

【问题讨论】:

  • 这能回答你的问题吗? $project in $lookup mongodb
  • 您只能在投影中指定 排除字段 - 这将保留您需要的所有字段。

标签: node.js mongodb


【解决方案1】:

如果您使用的是 mongodb >= 3.6,则可以在查找中使用管道:https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/#join-conditions-and-uncorrelated-sub-queries

所以您的代码将如下所示:

app.get('/getAllDetailById',(req,res)=>{
    if(db){
        // lookup
        db.collection("points").aggregate(
            [
                { "$addFields": { "enquiry_by": { "$toObjectId": "$enquiry_by" }}},
                { 
                    "$lookup" : {
                            from: "user",
                            let: { "enquiry_by": "$enquiry_by" },
                            pipeline: [
                                {
                                    "$match": {
                                        "$expr": {
                                            "$eq": ["$_id", "$$enquiry_by"] 
                                        }
                                    },
                                    "$project": {
                                        "$name": 1,
                                        "$username": 1,
                                    }
                                },
                            ],
                            as: "userDetails"
                       }
                },
                { $unwind: "$userDetails"},
             ]
        ).toArray()
        .then(result=>{
            console.log(result[0])
        }).catch(err=>{
                res.send(err)
        })
    }
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-20
    • 1970-01-01
    • 2022-11-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多