MongoDB 多个子查询

MongoDB multiple subqueries

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

这里有什么建议吗?

你可以试试,

  • $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