mongodb 如何匹配相等值并根据Mongo dB聚合结果返回true或false?

fcy6dtqo  于 2023-04-20  发布在  Go
关注(0)|答案(1)|浏览(152)

这是一个简单的喜欢和不喜欢的系统.我试图找到如果用户喜欢的职位或不.这是我所做的到目前为止,但我得到假,如果我给予ID而不是变量,那么它给我真的每一个文件.
到目前为止,我已经尝试了这个代码

[
  {
    $lookup: {
      from: "vouchers",
      localField: "voucherId",
      foreignField: "voucherObject._id",
      as: "voucher",
    },
  },
  {
    $unwind: {
      path: "$voucher",
      preserveNullAndEmptyArrays: true,
    },
  },
  {
    $unwind: {
      path: "$voucher.voucherObject",
      preserveNullAndEmptyArrays: true,
    },
  },
  {
    $lookup: {
      from: "profiles",
      localField: "userId",
      foreignField: "_id",
      as: "user",
    },
  },
  {
    $unwind: {
      path: "$user",
    },
  },
  {
    $lookup: {
      from: "likedposts",
      localField: "_id",
      foreignField: "postId",
      as: "liked",
    },
  },
  {
    $unwind: {
      path: "$liked",
      preserveNullAndEmptyArrays: true,
    },
  },
  {
    $unwind: {
      path: "$liked.userId",
      preserveNullAndEmptyArrays: true,
    },
  },
  {
    $project: {
      usId: "$userId",
      uId: "$liked.userId",
      equ: {
        $cond: {
          if: {
            $eq: ["$uId", "$usId"],
          },
          then: true,
          else: false,
        },
      },
    },
  },
]

这是响应数据

{
        "_id": "643e4ec0eab5d70d6d3b5750",
        "userId": "6438dd1af890514dff8fde36",
        "uId": "6438dd1af890514dff8fde36",
        "eq": false
    }

你知道为什么会这样吗?任何帮助都将非常感谢

ruarlubt

ruarlubt1#

当您指定$eq: ["$uId", "$usId"]时,它会从前一阶段的输出中查找uIdusId。由于这些在前一阶段中不存在,因此您的比较不会给予正确的结果。
相反,您应该使用$userId$liked.userId

$eq: ["$userId", "$liked.userId"]

相关问题