简体   繁体   English

Mongodb查询不适用于字符串

[英]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" 我有一个字符串serviceString和serviceString =“ test1”,“ test2”,“ test3”

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

This returns nothing from the DB BUT if I do this: 如果执行此操作,则不会从数据库BUT返回任何内容:

        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? 由于字符串是用户的输入,因此可以更改,因此我无法对查询中的变量进行硬编码,因此该怎么办?

$in is looking up for an array. $in正在寻找数组。

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 注意:您也可以使用var代替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 更多信息: https : //mongodb.github.io/node-mongodb-native/markdown-docs/queries.html#special-query-operators

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM