Shawn Varughese
Shawn Varughese

Reputation: 500

Mongodb Query does not work with string

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?

Upvotes: 0

Views: 777

Answers (2)

Natsathorn
Natsathorn

Reputation: 1528

$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

Upvotes: 1

Parshuram Kalvikatte
Parshuram Kalvikatte

Reputation: 1646

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
            }
        });

Upvotes: 0

Related Questions