mongodb 具有多个字段的Mongo查找查询

ruarlubt  于 2023-03-17  发布在  Go
关注(0)|答案(1)|浏览(131)

我有两个收款记录像这样

// collection_1
{
    "_id" : ObjectId("64100b43317d38bfe6238deb"),
    "email" : "email@google.com",
    "is_active" : true,
    "stage_id" : 2
}

另一个收藏记录是这样的

// collection_2
{
    "_id" : ObjectId("24003f7f345c72739747b6f9"),
    "collection_1_id":ObjectId("64100b43317d38bfe6238deb"),
    "stage_id" : 2,
    "link":"www.google.com"
}

因此,我希望从collection_1中查找查询,如下所示

select * from collection_1 
join collection_2 
where collection_1._id=collection_2.collection_1_id
and 
collection_1.stage_id=collection_2.stage_id

我已经搜索了,但我找不到匹配多个字段的方法

vcudknz3

vcudknz31#

您应该在$lookup中进行管道传输,如下所示:

db.c1.aggregate([
  {
    "$lookup": {
      "from": "c2",
      "let": {
        id: "$_id",
        stageId: "$stage_id"
      },
      "pipeline": [
        {
          "$match": {
            $expr: {
              "$and": [
                {
                  "$eq": [
                    "$$id",
                    "$collection_1_id"
                  ]
                },
                {
                  "$eq": [
                    "$$stageId",
                    "$stage_id"
                  ]
                }
              ]
            }
          }
        }
      ],
      "as": "docs"
    }
  }
])

Playground link.

相关问题