Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String or integer query in mongoDB for a single field

Tags:

mongodb

nosql

In MongoDB, there is field named vehId. It contains value in string as well in integer. like

{
"vehId" : "12"
}

or

{
"vehId" : 12
}

or

{
"vehId" : ""
}

If I do query as vehId as integer it return only vehId having value in Integer as for string it return only string. But I need a single query for both string and integer . Like

collection.find({"vehId" : <value> })

I need a single query that return all value. If I pass vehId as integer it also return values having vehId in string and vice-versa

like image 352
Ashutosh Avatar asked Dec 14 '15 06:12

Ashutosh


People also ask

How do I search for a specific field in MongoDB?

You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});

How do I change the datatype of a field in MongoDB?

You can change the data type of a field by using the data type selectors on the right of the field in the Atlas Cloud Cluster as well as MongoDB Compass . If you want to update it using Mongo shell or any specific drivers of MongoDB then you can refer to the $convert operator.

How do I search for a string in MongoDB?

Use the $text query operator to perform text searches on a collection with a text index. $text will tokenize the search string using whitespace and most punctuation as delimiters, and perform a logical OR of all such tokens in the search string.

Can I use regex in MongoDB query?

MongoDB provides the functionality to search a pattern in a string during a query by writing a regular expression. A regular expression is a generalized way to match patterns with sequences of characters. MongoDB uses Perl compatible regular expressions(PCRE) version 8.42 along with UTF-8 support.


1 Answers

So If you have situation like above, you can get your results easily with:

collection.find({"vehId" : { $in: [intval($vehId), $vehId}})
like image 89
Ashutosh Avatar answered Oct 18 '22 22:10

Ashutosh