收藏
回答

lookup联表查询,如何遍历数组,匹配对应的数据?

表1

"_id":"2a0398605f1114*****d69a167ebf9ed"
"name":"A_TL"
"alistArray":[100,101,200,201]


表二

"_id":"2a0398605f1114*****d69a167ebf9ed"
"alistID":"301"
"time":"20-10-10"
------------------------------------------------------
"_id":"2a0398605f1114*****d69a167ebf9ed"
"alistID":"100"
"time":"21-10-10"
------------------------------------------------------
"_id":"2a0398605f1114*****d69a167ebf9ed"
"alistID":"200"
"time":"20-12-10"
------------------------------------------------------
"_id":"2a0398605f1114*****d69a167ebf9ed"
"alistID":"201"
"time":"10-10-10"
------------------------------------------------------
"_id":"2a0398605f1114*****d69a167ebf9ed"
"alistID":"501"
"time":"25-10-10"


遍历【表1】里”alistArray“字段里的所有值,联表查询【表2】里的”alistID“相匹配的数据,

实现结果:

"_id":"2a0398605f1114*****d69a167ebf9ed"
"name":"A_TL"
"alistArray":[100,101,200,201]
"newlist":[
     {
  "_id":"2a0398605f1114*****d69a167ebf9ed"
  "alistID":"100"
  "time":"21-10-10"
      },
    {
  "_id":"2a0398605f1114*****d69a167ebf9ed"
  "alistID":"200"
  "time":"20-12-10"
     },
    {
  "_id":"2a0398605f1114*****d69a167ebf9ed"
  "alistID":"201"
  "time":"10-10-10"
      }
]




回答关注问题邀请回答
收藏

1 个回答

  • o0o有脾气的酸奶
    o0o有脾气的酸奶
    2020-07-17
    db.collection('table1').aggregate()
        .match({ _id:"2a0398605f1114*****d69a167ebf9ed" })
        .lookup({
          from'table2',
          let: {
            aliArr: '$alistArray'
          },
          pipeline: $.pipeline()
            .match(_.expr($.in(['$alistID''$$aliArr'])))
            .done(),
          as'newlist',
        })
        .end()
    

    若认为该回答有用,给回答者点个[ 有用 ],让答案帮助更多的人

    2020-07-17
    有用 5
    回复
登录 后发表内容
问题标签