【问题标题】:Mongodb lookup aggregation does not return relational dataMongodb查找聚合不返回关系数据
【发布时间】:2017-11-11 12:36:46
【问题描述】:

我正在尝试使用 Mongodb 中的查找聚合来模拟 Mongodb 中的联接并返回关系值。但它只返回当前集合的值,而不是与其相关的集合。

我有 2 个名为 wish_listproducts 的相关集合。 wish_list 包含已标记为愿望清单的产品,它包含产品集合中的 product_id。

wish_list的文档是这样的:

"_id"
"product_id"
"user_id"
"created_at"

如您所见,product_id 存在于此集合中,即来自products 集合的id

问题是当我尝试从wish_list 查询数据时,我想要products 集合中该产品的相关数据。它只返回来自wish_list 集合的数据(产品集合的结果是空数组)。

这是我执行的查询:

db.wish_list.aggregate([
  {$match: {
    user_id: "crawler"}
  }, 
  {$lookup: {
    from: "wish_list", 
    localField: "product_id",
    foreignField: "id",
    as: "products"}
  }
])

结果是这样的:

{
    "_id" : ObjectId("5a03024551195204432afcb6"),
    "product_id" : "com.thundanapps.thundpusthakam",
    "user_id" : "crawler",
    "created_at" : 1510146629,
    "products" : []
}

/* 2 */
{
    "_id" : ObjectId("5a0302565119520442375786"),
    "product_id" : "com.jott.android.jottmessenger",
    "user_id" : "crawler",
    "created_at" : 1510146646,
    "products" : []
}

P.S:我很确定 products 集合中存在等效数据。

P.S:反之亦然(从products 集合查询到with_list)时存在同样的问题。

【问题讨论】:

    标签: mongodb mongodb-query aggregation-framework


    【解决方案1】:

    您的$lookup 不正确。 如果您正在收集 wish_list 你必须说
    from: "product" 而不是 from: "wish_list"。还要确保foreignField 可能是_id 而不是id。如果您确定product 中的字段是id,那么您的聚合管道应该如下所示:

    db.wish_list.aggregate([
      {$match: {
        user_id: "crawler"}
      }, 
      {$lookup: {
        from: "product", 
        localField: "product_id",
        foreignField: "id",
        as: "products"}
      }
    ])
    

    from 中,您要添加要查看的集合,而不是您已经在聚合的集合。 localFieldforeignField 都必须与两个集合中的实际字段匹配。在as 中,您可以随意命名该字段

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-13
      • 1970-01-01
      • 2022-01-03
      • 2017-07-19
      • 2023-03-30
      • 2020-06-24
      • 2018-12-10
      • 1970-01-01
      相关资源
      最近更新 更多