【问题标题】:How to use $lookup as INNER JOIN in MongoDB Aggregation?如何在 MongoDB 聚合中使用 $lookup 作为 INNER JOIN?
【发布时间】:2017-12-06 12:30:25
【问题描述】:

我在聚合查询中使用了$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's 文档

预期结果

/* 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 我想你没有得到我的问题,我更新了我的预期结果
  • 你试过我的查询了吗?

标签: mongodb aggregation-framework


【解决方案1】:

只需添加$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
        }
    ]
}

【讨论】:

  • 添加了我的查询结果。
  • 这样有效率吗?
猜你喜欢
  • 2016-10-08
  • 1970-01-01
  • 2020-07-12
  • 2021-12-01
  • 2018-12-20
  • 1970-01-01
  • 2022-01-05
  • 2023-03-09
  • 1970-01-01
相关资源
最近更新 更多