【问题标题】:MongoDB multiple subqueriesMongoDB 多个子查询
【发布时间】:2020-12-15 11:02:15
【问题描述】:

我对 no-sql 数据库有点陌生,所以我在这里有一个关于子查询的问题。

让我们想象一下下面的结构:

Type (_id, offerId)
Offer (_id, typeId, productId)
Product (_id, subId)

我需要通过 subId 找到所有类型。

我不知道它在 MongoDB 中是如何工作的,在 SQL 中我会做类似的事情:

select * from Type where offerId in 
  (select _id from Offer where productId in
    (select _id from Product where subId = 'test'));

对于 MongoDB,我尝试创建某种聚合查询,但它不起作用:

{
  "aggregate": "Type",
  "pipeline": [
    {
      "$lookup": {
        "from": "Offer",
        "localField": "_id",
        "foreignField": "typeId",
        "as": "subOffer"
      }
    },
    {
      "$lookup": {
        "from": "Product",
        "localField": "_id",
        "foreignField": "subOffer.productId",
        "as": "subProduct"
      }
    },
    {
      "$match": {
        "subProduct.subId": "test"
      }
    },
    {
      "$unwind": "$subProduct"
    },
    {
      "$unwind": "$subOffer"
    }
  ]
}

这里有什么建议吗?

【问题讨论】:

    标签: mongodb mongodb-query mongodb-lookup


    【解决方案1】:

    你可以试试,

    • $lookup on offer 使用管道收集
    • $match 类型 ID
    • $lookup on product 使用管道收集
    • $match 字段 subIdproductId
    • $match 产品不是 [] 为空
    • $match 报价不是[] 为空
    • $project删除报价字段
    db.type.aggregate([
      {
        $lookup: {
          from: "offer",
          let: { tid: "$_id" },
          as: "offer",
          pipeline: [
            { $match: { $expr: { $eq: ["$$tid", "$typeId"] } } },
            {
              $lookup: {
                from: "product",
                as: "product",
                let: { pid: "$productId" },
                pipeline: [
                  {
                    $match: {
                      $and: [
                        { subId: "test" },
                        { $expr: { $eq: ["$_id", "$$pid"] } }
                      ]
                    }
                  }
                ]
              }
            },
            { $match: { product: { $ne: [] } } }
          ]
        }
      },
      { $match: { offer: { $ne: [] } } },
      { $project: { offer: 0 } }
    ])
    

    Playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 2015-03-01
      • 1970-01-01
      • 2017-10-01
      • 1970-01-01
      • 2019-05-09
      • 1970-01-01
      相关资源
      最近更新 更多