如何在mongoDB的嵌套数据中使用聚合$ lookup?

迈克尔·莱斯特

我有这样的收藏:

// 任务

[
  {_id: '123', _user: '345', _solutions: ['567', '678'] }
]

//解决方案

[
  {  _id: '567', _task: '123', _user: '345' },
  {  _id: '678', _task: '123', _user: '345' }
]

//用户

[
 { _id: '345', name: 'Tom' }
]

使用此代码:

await db
    .collection<Task>('tasks')
    .aggregate([
      { $match: { _id: id } },
      {
        $lookup: {
          from: 'solutions',
          // I guess here should be pipeline  
          localField: '_solutions',
          foreignField: '_id',
          as: '_solutions',
        },
      },
      { $lookup: { from: 'users', localField: '_user', foreignField: '_id', as: '_user' } },
    ])

我得到如下结果:

task = {
  _id: 5e14e877fa42402079e38e44,
  _solutions: [
    {
      _id: 5e15022ccafcb4869c153e61,
      _task: 5e14e877fa42402079e38e44,
      _user: 5e007403fd4ca4f47df69913, <-- this should be userObject instead
    },
    {
      _id: 5e164f31cafcb4869c153e62,
      _task: 5e14e877fa42402079e38e44,
      _user: 5e007403fd4ca4f47df69913, <-- this should be userObject instead
    }
  ],
  _user: [
    {
      _id: 5e007403fd4ca4f47df69913,
      _solutions: [Array],
      _tasks: [Array],
    }
  ]
}

而且我不知道如何$lookup进入_solutions._user-所以我将使用确切的用户对象代替objectId。

米克尔

您可以运行带有自定义管道的$ lookup进行外部查找,并使用常规管道供用户使用:

db.tasks.aggregate([
    {
        $match: {
            _id: "123"
        }
    },
    {
        $lookup: {
            from: "solutions",
            let: { solutions: "$_solutions" },
            pipeline: [
                { $match: { $expr: { $in: [ "$_id", "$$solutions" ] } } },
                {
                    $lookup: {
                        from: "users",
                        localField: "_user",
                        foreignField: "_id",
                        as: "_user"
                    }
                },
                { $unwind: "$_user" }
            ],
            as: "_solutions",      
        }    
    }  
])

蒙哥运动场

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章