简体   繁体   中英

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


I'm doing a school project and I'm stuck :(
When the url is ".../?liked=true" I want to show only likedInterns.
likedInterns is an array with IDs = ['628f8f1f7a7a944bd8927c1b', '6291241d80feece846cbc104', '628f8f1f7a7a944bd8927c1a']
I can't find the correct query for MongoDB, "$elemMatch: likedInterns" is not working I want to find an Intern array that contains one of the elements from likedInterns array. Please help
 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]; }

Try to build your filter before the query and use the $in operator

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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM