This is a user document in my mongodb, there are many other user documents as well. And have an array of interests like this
myInterests['gaming','reading']
This array can be dynamic in the future
I want to write a query in which I can get the list of those users who have these 2 interests or atleast 1 of them, how can I write a query for this?
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);
});
I have tried this code but this code is getting me the list of those users only which have these 2 interests. I want to get those users too which have at least 1 of the elements of this array.
CodePudding user response:
The myInterests
is already an array.
The query should be like this
interests: {
$in: myInterests,
}
instead of
interests: {
$in: [myInterests],
}
Otherwise, it looks for the exact matches using the 2D array.
Working playground => https://mongoplayground.net/p/D2_JwvBUn3k