MongoDB 查找包含另一个数组中的元素之一的数组

MongoDB find an array that contains one of the elements from another array


我正在做一个学校项目,但我被卡住了:(
当 url 为“.../?liked=true”时,我只想显示喜欢的实习生。
likedInterns 是一个 IDs = ['628f8f1f7a7a944bd8927c1b', '6291241d80feece846cbc104', '628f8f1f7a7a944bd8927c1a']
的数组 我找不到 MongoDB 的正确查询,“$elemMatch: likedInterns”不起作用 我想找到一个包含 likedInterns 数组中的元素之一的实习生数组。 请帮忙
  const likedInterns = company.likedInterns;
  const liked = url.searchParams.get("liked");
  const interns = await db.models.intern
    .find(
      search
        ? {
            name: { $regex: new RegExp(search, "i") },
          }
        : {} 
      /* Show only liked interns - Not working */,
      liked
        ? {
           _id: { $elemMatch: likedInterns  },
          }
        : {}
    )
    .sort({ updatedAt: -1 });
  return [interns, tags, userId, companyId];
}

尝试在查询之前构建您的 filter 并使用 $in 运算符

const likedInterns = company.likedInterns;
const liked = url.searchParams.get('liked');
let filter = {};
if (search) filter = { ...filter, name: { $regex: new RegExp(search, 'i') } }
if (liked) filter = { ...filter, { _id: { $in: likedInterns } } }
const interns = await db.models.intern
  .find(filter)
  .sort({ updatedAt: -1 });
return [interns, tags, userId, companyId];