MongoDB-查找值是否与数组中的第二个元素匹配

yrdbyhpb  于 2022-10-22  发布在  Go
关注(0)|答案(2)|浏览(302)

尝试通过检查变量(userId)是否与users数组中的第二个元素匹配来从集合返回此文档。
我创造了一个Playground。预期结果是用户文档xyz,因为这是唯一喜欢rrr的用户,而用户rrr不喜欢back-https://mongoplayground.net/p/WI7hqR7SIMh
预期结果:

[
  {
    "count": 1,
    "users": [
      {
        "_id": "xyz",
        "group": 1,
        "name": "xyyy"
      }
    ]
  }
]

我的查询如下,其中变量userId是xw5vk1s,是上面数组中的第二个元素。我正在检查的两个条件是like: trueuserId = second element is users array

const users = await db
    .collection('users')
    .aggregate([
      {
        $lookup: {
          from: "likes",
          let: {userId: "$_id"},
          pipeline: [{$match: {$expr: {$and: [{like: true, "users.1": userId} ]}}}],
          as: "valid"
        }
      },
      {$match: {
          "valid.0": {$exists: true},
        }
      },
      {$unset: ["valid"]},
      {$group: {_id: 0, users: {$push: "$$ROOT"}, count: {$sum: 1}}}
    ])

查询不起作用。

s4chpxco

s4chpxco1#

一种选择是使用两个$lookup
1.首先找出“喜欢”的伴侣。
1.仅限未配对的$match
1.获取user数据并格式化响应

db.partnership.aggregate([
  {$match: {$expr: {$eq: [{$last: "$users"}, "rrr"]}}},
  {$lookup: {
      from: "partnership",
      let: {likes: {$last: "$users"}, me: {$first: "$users"}},
      pipeline: [
        {$match: {
            $expr: {$and: [
                {$eq: [{$last: "$users"}, "$$me"]},
                {$eq: [{$first: "$users"}, "$$likes"]}
              ]
            }
          }
        }
      ],
      as: "paired"
    }
  },
  {$match: {"paired.0": {$exists: false}}},
  {$project: {_id: 0, user: {$first: "$users"}}},
  {$lookup: {
      from: "users",
      localField: "user",
      foreignField: "_id",
      as: "user"
  }},
  {$project: {user: {$first: "$user"}}},
  {$replaceRoot: {newRoot: "$user"}}
])

了解它在playground example上的工作原理

tag5nh1u

tag5nh1u2#

希望这能解决你的问题

https://mongoplayground.net/p/8Ax_NaRhfHs

[
  {
    $addFields: {
      secondItem: {
        $arrayElemAt: [
          "$users",
          1
        ]
      }
    }
  },
  {
    $match: {
      $and: [
        {
          users: {
            $in: [
              "$users",
              "xw5vk1s"
            ]
          }
        },
        {
          $expr: {
            $eq: [
              "$secondItem",
              "xw5vk1s"
            ]
          }
        }
      ]
    }
  }
]

相关问题