【问题标题】:lookup with add extra field in mongodb在 mongodb 中添加额外字段的查找
【发布时间】:2021-09-30 07:38:05
【问题描述】:

我的 OBJ

[{
_id:XXXXXXXXXX,
role:admin
},
{
_id:XXXXXXXXXX,
role:superUser
}]

并且需要使用聚合的结果如何使用聚合来解决这个问题

[{
name:'username'
role:'test'
}

]

【问题讨论】:

    标签: node.js mongodb lookup aggregation


    【解决方案1】:

    我想你需要以下内容

    let db1 = db.get().collection(`temp1`);
        let db2 = db.get().collection(`temp2`);
    
        await db1.aggregate([
            {
                $lookup: {
                    from: "temp2",
                    localField: "_id",    // field in the orders collection
                    foreignField: "_id",  // field in the items collection
                    as: "users"
                }
            },
            {
                $replaceRoot: { newRoot: { $mergeObjects: [{ $arrayElemAt: ["$users", 0] }, "$$ROOT"] } }
            },
            { $project: { users: 0 } }
        ]).toArray()
    

    【讨论】:

      猜你喜欢
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      • 2015-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-11
      相关资源
      最近更新 更多