Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
604 views
in Technique[技术] by (71.8m points)

mongodb 怎么实现在第一次多表查询的基础上进行第二次多表查询?

Project 查询到了 projectMember 的数据

const res = await ctx.model.Project
      .aggregate([
        {
          $match: { title },
        },

        {
          $lookup: {
            from: 'projectMember',
            localField: '_id',
            foreignField: 'project_id',
            as: 'members',
          },
        },
      ])

多了一个 members 字段

[
    {
        "_id": "5eaab0716548c615306ed0fb",
        "visible": "公开",
        "type": "小说",
        "title": "守灯人2",
        "summary": "孤独一直都在,从始至终。",
        "user_id": "5eaa88c44fe6dc2ef013b8b8",
        "create_at": "2020-04-30T11:03:13.861Z",
        "update_at": "2020-04-30T11:03:13.862Z",
        "__v": 0,
        "members": [
            {
                "_id": "5eaab07144a25541579fa966",
                "project_id": "5eaab0716548c615306ed0fb",
                "user_id": "5eaa88c44fe6dc2ef013b8b8",
                "__v": 0,
                "type": "admin"
            }
        ]
    }
]

现在,我想要,继续多表查询 members 里所有文档的 user_id (关联 User 表),请问怎么实现?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

聚合的数据是一个流,可以再后面持续添加各种操作符号:

  1. $unwind 把 llokup 的数据拆分为内嵌的对象,而不是数组结构
  2. $lookup 添加其他数据
  3. $match 查询条件,可以直接对 lookup 引入的其他字段查询

这样是不走索引的,数据量大,效率很低.mongo 还是需要尽量避免联表查询(查询条件是另一个表的),当时查询条件是当前表的,吧match放在第一个就好了,再通过lookup引入其他数据,这样性能也不会有影响

大概是这样,

{"$match":{}},
{
  $lookup: {
    from: 'projectMember',
    localField: '_id',
    foreignField: 'project_id',
    as: 'members',
  },
},
{
    "$unwind":{"path":"$members"},
    "preserveNullAndEmptyArrays": true
},
{"$match":{}},

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...