Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find records where field type is string

I have this records :

{id : 1 , price : 5}
{id : 2 , price : "6"}
{id : 3 , price : 13}
{id : 4 , price : "75"}

I want to build a query that get just record who have price with type "string"

so, it will get :

{id : 2 , price : "6"}
{id : 4 , price : "75"}
like image 374
user3134277 Avatar asked Mar 10 '23 07:03

user3134277


2 Answers

You can use the $type query operator to do this:

db.test.find({price: {$type: 2}})

If you're using MongoDB 3.2+, you can also use the string alias for the type:

db.test.find({price: {$type: 'string'}})
like image 123
JohnnyHK Avatar answered Mar 27 '23 05:03

JohnnyHK


While @JohnnyHK's answer is absolutely correct in most cases, MongoDB also returns documents where field is an array and any of the elements in that array have that type (docs). So for example, the document

{ 
  _id: 1,
  tags: ['123']
}

is returned for the query Books.find({ tags: { $type: "string" } }) as well. To prevent this, you can adjust the query to be

Books.find({
  tags: {
    $type: "string",
    $not: {
      $type: "array"
    }
  }
})
like image 20
Ruben Helsloot Avatar answered Mar 27 '23 04:03

Ruben Helsloot