0

I am trying to get documents in the database that match the string but it does not work when i pass in the variable.

I have a string serviceString and serviceString = "test1", "test2", "test3"

        query = db.collection('Services').find({
            'Service': {
                $in: [serviceString]
            }
        });

This returns nothing from the DB BUT if I do this:

        query = db.collection('Services').find({
            'Service': {
                $in: ["test1", "test2", "test3"]
            }
        });

It works and returns what I need.

Do you know why its not working, I am thinking the string is putting commas in as a string. Whats a way I can do this because the string is a input from a user so it can change so I cant hard code the variables in the query?

1
  • Try this query = db.collection('Services').find({ 'Service': { $in: serviceString.split(',') } }); Commented Nov 17, 2016 at 13:55

2 Answers 2

1

$in is looking up for an array.

So, It's better to create an array of string you want to find.

let serviceString = ["test1", "test2", "test3"];

Note : You can also use var instead of let here

Then your query will look likes :

let serviceString = ["test1", "test2", "test3"];
query = db.collection('Services').find({
       'Service': {
           $in: serviceString
      }
});

more information : https://mongodb.github.io/node-mongodb-native/markdown-docs/queries.html#special-query-operators

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

Comments

0

You need to know what are you doing first you are passing a complete string

"test1","test2","test3"

Do something like this

var serviceString = ["test1","test2","test3"];

and then your query

   query = db.collection('Services').find({
            'Service': {
                $in: serviceString
            }
        });

Comments

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.