1

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

这里有什么建议吗?

4

1 回答 1

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 } }
])

操场

于 2020-08-26T16:31:56.940 回答