MongoDB多个子查询

时间:2020-08-26 15:44:11

标签: mongodb mongodb-query mongodb-lookup

我是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"
    }
  ]
}

这里有什么建议吗?

1 个答案:

答案 0 :(得分:1)

您可以尝试

    使用管道通过
  • $lookup收集offer
  • $match类型ID
  • 使用管道通过
  • $lookup收集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

相关问题