首页 > 解决方案 > MongoDB多对多查找

问题描述

我有以下情况。

Offer {
id,
name
}

OfferCategory {
 offerId,
 categoryId
}

Category {
id,
name
}

我想检索 al Offers 及其类别,包括同一查询中的名称(在此之前,我使用 geoNear 步骤进行过滤)。我有这个,但它带来了一个空categoriesObj数组。我认为localField最后一个$lookup操作不正确:

db.Offer.aggregate([
{
    $geoNear: {
        near: { type: "Point", coordinates: [ -58, -34 ] },
        distanceField: "dist.calculated",
        maxDistance: 200,
        spherical: true
    }
},
{
    $lookup: {
                from: "OfferCategory",
                localField: "_id",
                foreignField: "offerId",
                as: "categories"
    }
},
{
    $lookup: {
                from: "Category",
                localField: "categories._id",
                foreignField: "_id",
                as: "categoriesObjs"
    }
},
]);

标签: mongodb

解决方案


您可以将此聚合与 mongoDB 版本 ^3.6 一起使用

db.offers.aggregate([
  { $geoNear: {
      near: { type: "Point", coordinates: [ -58, -34 ] },
      distanceField: "dist.calculated",
      maxDistance: 200,
      spherical: true
  }},
  { $lookup: {
      from: "offerCategory",
      let: { offerId: "$_id" },
      pipeline: [
        { $match: { $expr: { $eq: ["$$offerId", "$offerId"] } } },
        { $lookup: {
            from: "Category",
            let: { categoryId: "$categoryId" },
            pipeline: [{ $match: { $expr: { $eq: ["$$categoryId", "$id"] } } }],
            as: "cateogries"
        }}
      ],
      as: "offerCategories"
    }
  }
]);

推荐阅读