11

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

4
  • 1
    So just supply both the integer and string values as an argument to $in. Commented Dec 14, 2015 at 6:21
  • @BlakesSeven I am getting only one value, it may be string or integer Commented Dec 14, 2015 at 6:24
  • 4
    Blakes is asking to run query like collection.find({"vehId" : { $in: [12, "12"}}) Commented Dec 14, 2015 at 6:28
  • Anyway I got the idea how to do it. Thanks @BlakesSeven Commented Dec 14, 2015 at 6:28

2 Answers 2

5

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

collection.find({"vehId" : { $in: [intval($vehId), $vehId}})
Sign up to request clarification or add additional context in comments.

2 Comments

I strongly don't recommend this approach, unless you're sure that $vehId is always going to contain only numeric value. For example, if $vehId = '123abc', then your script will match 123 AND '123abc' !
In db $vehId is always integer and its auto incremented.
0
collection.find({ $or: [{"vehId":value}, {"vehId": intval(value)}})

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.