返回所有的年龄都是ints
问题描述:
我正在学习Mongo并试用它的功能。我有一个包含名称和年龄的文档的集合。年龄通常是一个数字,但有时也可以是一个字符串,例如:返回所有的年龄都是ints
{
name: "example",
age: 20
}
{
name: "exampleTwo",
age: "Not informed"
}
{
name: "exampleThree",
age: 21
}
我知道我可以,而且也应该,插入默认号码,如-1或0非知情年龄,但我正在尝试和测试mongo特性。在这种情况下,在同一个集合中拥有不同类型的文档。
所以我想做一个查询,返回所有具有年龄作为数字类型的文档。因为我知道我可以使用查询这个具体的例子:
db.example.find({age: { $ne: "Not Informed" }})
但我想知道如果有可能使一个不太具体的查询,如前面提到的,一个是返回具有岁作为一个号码的所有文件?检查值的类型而不是值本身?
答
因此,这始终工作:
db.example.find({ age : { $type : 16 } })
这工作,因为蒙戈3.2:
db.example.find({ age : { $type : 'int' } })
这就是[$类型](https://docs.mongodb.com/manual/reference/operator/query/type /)查询是针对的 –