0

I'm using mongoDB version 3.2. and i want to check if a string is exist in an array of string, i want to use the regex so if just a part of the given string is exist in a string in the array, that record should be returned. here's an example of a record:

{
    name: "initiative 1",
    portfolioItems: ["Non clinical", "ITS portfolio", "Lean"]
}

the following query does not work:

db.collection.aggregate([
    {
        $match:
            { 'portfolioItems' : { $in: [/term/] } }
    }
])

is there anyway to achieve that ?

2 Answers 2

1

Try this one.

db.collection.aggregate([
{
    $match:
    {"portfolioItems":{'$regex':"^it", '$options': 'i'}}
}
])

The symbol ^ used to start from the first of string. If u don't need it. You can remove it.

Your query become

 {
    $match:
    {"portfolioItems":{'$regex':"^"+term, '$options': 'i'}}
}
Sign up to request clarification or add additional context in comments.

3 Comments

still the query return no results.
I run the same in my local using Robo3T and worked fine.
yes it works fine on shell too. bug in my node app didn't work !!
0

You have to match the pattern in each element of array. Try this :

{ 'portfolioItems' : { $regex: [/term/] } }

4 Comments

But there is no element which contains "term", so results will be empty. Have you tried another element.
{ $match: {"portfolioItems":{'$regex':"^it", '$options': 'i'}} } Try with this
term is javascript variable used to store the search term. + used to concatenate with ^. It is not a static string like "term" that you entered in the comment.
Thank you very much for informing me. I didn't have much idea about this

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.