1

Let me first of all explain the situation. I have made advanced search which is used to search posts and profiles. I have made switch button which shows post search or profile search. After receiving all the details on the server. I have made this query:

await Profile.aggregate([
    {
        $match: {
            $or: [
                {"company": {$regex: profile.company}},
                {"skills": {$all: profile.skills}},
                {"experience.company" :{$in: [ profile.experience.company]}}
            ]
        }
    },
    {
        $skip: req.params.page ? req.params.page - 1 : 0 // make sure this can't be -1
    },
    {
        $limit: 11
    },
    {
        $lookup: {
            from: "user",
            localField: "user",
            foreignField: "_id",
            as: "user"
        }
    },
    {
        "$unwind": "$user"
    }
])

But lets say company is undefined and gives me the following error $regex must be a string. How to search about this fields that are defined or not empty string? Also I'm not sure if that piece of code is right:

{"experience.company" :{$in: [ profile.experience.company]}}

And the next question is how search for user.name company and skills at once? Should I lookup first and then match or what? (Sorry about this questions, but I'm new to MongoDB)

1 Answer 1

1

To prevent the $regex error when comparing the undefined fields, you can filter the fields at the beginning.

Example:

db.collection.aggregate([
  {
    $match:{
      company: {
        $exists: true
      }
    }
  }
])

"And the next question is how search for user.name company and skills at once?"

You can do it in one aggregation pipeline at a time. That doesn't matter. but related to which query will be placed at the beginning of the pipeline depends on your data structure and what you are looking for.

Sign up to request clarification or add additional context in comments.

1 Comment

Hello! I can you give me an example with your code about $exists ( with mine fields company skills..). Lets say I have an Profile collection with company and skills and user collections with name in it I want to compare search queries to that and if any of these 3 match I want to return. Also is there any possible way to count them so I can return them sorted by best match and then less and less and is this valid code: {"experience.company" :{$in: [ profile.experience.company]}} because returns all the profiles(match them all or something like that) Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.