Find at least one result within a mongoDB array

Asked

Viewed 54 times

-1

I would like to return the user posts if they have at least one of the tags similar to the post

For example:

  • User tags ["react","c#","node"]
  • Post tags ["c#","sqlserver","asp.net"]

How the user has the tag C# and the post also, I would like to include it in the result of the consultation, through the documentation I could only get to the part where I return if the array user.tags is entirely contained in posts.tags

   const user = await Users.findById(user_id);
    if (!user) {
        return res.status(401).send('Usuário inválido');
    }
    const posts = await Posts.find({ tags: { $all: user.tags } });

https://docs.mongodb.com/manual/tutorial/project-fields-from-query-results/

  • Could change the $all for $in.

  • It worked! Is there anywhere I can find more references to $all and $in?

  • Yes, the documentation for mongodb https://docs.mongodb.com/manual/reference/operator/aggregation/in/

1 answer

0

According to the documentation to achieve the desired result just change the operator $all for $in

A possible solution would be:

const posts = await Posts.find({ tags: { $in: user.tags } });

Browser other questions tagged

You are not signed in. Login or sign up in order to post.