Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to match values in mongodb array with another array

User Document

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading