如何在 MongoDB 聚合中使用 $lookup 作为 INNER JOIN?

11

我在聚合查询中使用了$lookup,但我发现它的作用类似于LEFT OUTER JOIN

我想要通过$lookup获取精确匹配的文档(INNER JOIN)。

有什么方法可以实现吗?

这是我的inventory集合:

/* 1 */
{
    "_id" : 1,
    "sku" : "abc",
    "description" : "product 1",
    "instock" : 120
}

/* 2 */
{
    "_id" : 2,
    "sku" : "def",
    "description" : "product 2",
    "instock" : 80
}

/* 3 */
{
    "_id" : 3,
    "sku" : "ijk",
    "description" : "product 3",
    "instock" : 60
}

/* 4 */
{
    "_id" : 4,
    "sku" : "jkl",
    "description" : "product 4",
    "instock" : 70
}

/* 5 */
{
    "_id" : 5,
    "sku" : null,
    "description" : "Incomplete"
}

这是我的orders集合

/* 1 */
{
    "_id" : 1,
    "item" : "abc",
    "price" : 12,
    "quantity" : 2
}

/* 2 */
{
    "_id" : 2,
    "item" : "jkl",
    "price" : 20,
    "quantity" : 1
}

/* 3 */
{
    "_id" : 10,
    "item" : "jklw",
    "price" : 20,
    "quantity" : 1
}

这是一个查询

db.getCollection('inventory').aggregate([
   {
     $lookup:
       {
         from: "orders",
         localField: "sku",
         foreignField: "item",
         as: "inventory_docs"
       }
  }
])

在这个查询中,我会得到所有与orders文档匹配的inventory文档。

预期结果

/* 1 */
{
    "_id" : 1,
    "sku" : "abc",
    "description" : "product 1",
    "instock" : 120,
    "inventory_docs" : [ 
        {
            "_id" : 1,
            "item" : "abc",
            "price" : 12,
            "quantity" : 2
        }
    ]
}

/* 2 */
{
    "_id" : 4,
    "sku" : "jkl",
    "description" : "product 4",
    "instock" : 70,
    "inventory_docs" : [ 
        {
            "_id" : 2,
            "item" : "jkl",
            "price" : 20,
            "quantity" : 1
        }
    ]
}

你能展示一下期望的结果吗? - Neodan
@Neodan,我觉得你没有理解我的问题,我更新了我的期望结果。 - abdulbarik
你试过我的查询吗? - Neodan
1个回答

18

只需添加$match管道阶段,可以跳过具有空的inventory_docs字段的文档。没有其他方法可以实现。

查询:

db.getCollection('inventory').aggregate([
    {
        $lookup: {
            from: "orders",
            localField: "sku",
            foreignField: "item",
            as: "inventory_docs"
        }
    },
    {
        $match: {
            "inventory_docs": {$ne: []}
        }
    }
])

结果:

{
    "_id" : 1.0,
    "sku" : "abc",
    "description" : "product 1",
    "instock" : 120.0,
    "inventory_docs" : [ 
        {
            "_id" : 1.0,
            "item" : "abc",
            "price" : 12.0,
            "quantity" : 2.0
        }
    ]
}

{
    "_id" : 4.0,
    "sku" : "jkl",
    "description" : "product 4",
    "instock" : 70.0,
    "inventory_docs" : [ 
        {
            "_id" : 2.0,
            "item" : "jkl",
            "price" : 20.0,
            "quantity" : 1.0
        }
    ]
}

添加了我的查询结果。 - Neodan
这个有效吗? - Stepan Yakovenko
查找仅删除特定集合,但使用$ne时,它将仅返回与该条件完全匹配的数据。这对我非常有帮助!谢谢!! - Anonymous

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接