返回所有年龄的整数

时间:2016-09-16 12:59:07

标签: mongodb

我正在研究Mongo并试用它的功能。我有一个包含姓名和年龄的文件的集合。年龄通常是一个数字,但有时它可以是一个字符串,例如:

{
name: "example",
age: 20 
}

{
name: "exampleTwo",
age: "Not informed"
}

{
name: "exampleThree",
age: 21
}

我知道我可以,也可能应该为非知情年龄插入默认数字,如-1或0,但我正在尝试并测试mongo功能。在这种情况下,在同一个集合中包含具有不同类型的文档。

所以我想创建一个查询,返回所有年龄为数字类型的文档。对于这个具体的例子我知道我可以使用查询:

db.example.find({age: { $ne: "Not Informed" }})

但我想知道是否可以制作一个不太具体的查询,如前所述,返回所有年龄为数字的文档?检查值的类型而不是值本身?

1 个答案:

答案 0 :(得分:1)

"Changed in version 3.2: $type operator accepts string aliases for the BSON types in addition to the numbers corresponding to the BSON types."

因此,这总是有效:

db.example.find( { age : { $type : 16 } } )

这是因为Mongo 3.2:

db.example.find( { age : { $type : 'int' } } )