You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写MongoDB查询,匹配两个数组的值,筛选有至少一个共同兴趣的用户

问题根因

你当前代码的问题在于对$in操作符的传值格式有误:你从req.user中解构出的myInterests本身就是数组类型(例如['gaming','reading']),又额外套了一层数组包裹,最终传入$in的实际值是[['gaming','reading']],此时查询逻辑变成了匹配interests字段包含['gaming','reading']这个整体元素的用户,自然只有同时完全命中两个兴趣的用户才会被查询到。


需求1:查询至少匹配1个兴趣的用户

直接移除$in参数外层的数组包裹即可,$in操作符本身就支持传入数组,匹配字段包含数组中任意一个元素的文档:

router.get("/", auth, async function (req, res) {
  const { interests: myInterests } = req.user;
  const users = await User.find({
    interests: { $in: myInterests },
  }).select({ email: 1, interests: 1 });
  console.log(users);
});

需求2:可切换「匹配至少一个」/「匹配全部兴趣」

如果需要同时支持两种查询逻辑,可以根据参数选择对应操作符:

  • 匹配至少一个:用$in
  • 匹配myInterests中所有兴趣:用$all
    示例代码:
router.get("/", auth, async function (req, res) {
  const { interests: myInterests } = req.user;
  const { matchAll = false } = req.query; // 前端传matchAll=true则查询同时匹配所有兴趣的用户
  const queryOp = matchAll ? '$all' : '$in';
  const users = await User.find({
    interests: { [queryOp]: myInterests },
  }).select({ email: 1, interests: 1 });
  console.log(users);
});

注:$all操作符的作用是匹配interests数组中包含传入数组的所有元素的文档,元素顺序不影响匹配结果。

内容的提问来源于stack exchange,提问作者Saad8113

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 21:36:01