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"}
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'}})
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"
}
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With