【问题标题】:MongoDB aggregation lookup pipeline queryMongoDB聚合查找管道查询
【发布时间】:2020-09-29 12:27:57
【问题描述】:

我正在寻求有关 MongoDB 查找聚合查询的帮助。

我正在尝试加入两个系列,即“cafe”和“stamp”。在查找过程中,我想匹配给定咖啡馆的邮票,然后进一步对结果进行排序并将结果限制为 10。

相关的 id 字段是:“_id”表示咖啡馆收藏,“cafeId”表示邮票收藏。

以下是我想出的,但是在尝试通过给定集合之间的 id 进行匹配时似乎存在问题。我相信这可能与 Mongo 没有将它们视为 ObjectID 相关,但我不确定。

db.cafe.aggregate([
      {
        $lookup: {
          from: "stamp",
          as: "stamps",
          let: {
            id: "$_id",
            name: "$name"
          },
          pipeline: [
            { $project: { id:1, cafeId: { $toObjectId: "$$id"}, name:1 } },
            { $match: { expr: { $eq: ["$$cafeId", "$cafeId"] } } },
            { $sort: { stampDate: -1 } },
            { $limit: 10 }
          ]
        }
      }
    ]);

【问题讨论】:

    标签: database mongodb mongoose nosql


    【解决方案1】:

    设法弄清楚如何实现我想要的。将这里留给其他试图达到相同结果的人。

    db.cafe.aggregate([
      {
        $lookup: {
          from: "stamp",
          as: "stamps",
          let: {
            id: "$_id",
            name: "$name" //All cafes variables,
          },
          pipeline: [
            {
              $project: {
                cafeId: 1,
                stampDate: 1,
                stampId: 1,
                cafeId: 1,
                status: 1,
                userId: { $toObjectId: "$userId" }
              }
            },
            {
              $match: {
                $expr: {
                  $and: [
                    {
                      $eq: [{ $toObjectId: "$$id" }, { $toObjectId: "$cafeId" }]
                    },
                    {
                      $eq: [
                        { $toObjectId: "$userId" },
                        mongoose.Types.ObjectId(req.user._id)
                      ]
                    }
                  ]
                }
              }
            }
          ]
        }
      }
    ]);
    

    【讨论】:

    • “$userId”从何而来?
    猜你喜欢
    • 1970-01-01
    • 2023-02-25
    • 2020-07-27
    • 2020-12-17
    • 2020-06-13
    • 1970-01-01
    • 1970-01-01
    • 2020-11-23
    • 1970-01-01
    相关资源
    最近更新 更多