查找字段类型为字符串的记录

find records where field type is string

我有这个记录:

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

我想构建一个查询,只获取价格类型为 "string"

的记录

所以,它将得到:

{id : 2 , price : "6"}
{id : 4 , price : "75"}

您可以使用 $type 查询运算符来执行此操作:

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

如果您使用的是 MongoDB 3.2+,您还可以为类型使用字符串别名:

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

虽然@JohnnyHK 的答案在大多数情况下是绝对正确的,但 MongoDB 也 returns 文档其中 field 是一个数组,并且该数组中的任何元素都具有该类型(docs).例如,文档

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

也会为查询 Books.find({ tags: { $type: "string" } }) 返回。为了防止这种情况,您可以将查询调整为

Books.find({
  tags: {
    $type: "string",
    $not: {
      $type: "array"
    }
  }
})