要检查MongoDB中的field是否为数字,请使用$type运算符。以下是语法
db.yourCollectionName.find({youtFieldName: {$type:"number"}}).pretty();
首先让我们创建一个包含文档的集合
> db.checkIfFieldIsNumberDemo.insertOne({"StudentName":"John","StudentAge":23}); { "acknowledged" : true, "insertedId" : ObjectId("5c9ec75dd628fa4220163b83") } >db.checkIfFieldIsNumberDemo.insertOne({"StudentName":"Chris","StudentMathScore":98,"StudentCountryName":"US"}); { "acknowledged" : true, "insertedId" : ObjectId("5c9ec77cd628fa4220163b84") } >db.checkIfFieldIsNumberDemo.insertOne({"StudentName":"Robert","StudentCountryName":"AUS"}); { "acknowledged" : true, "insertedId" : ObjectId("5c9ec7a4d628fa4220163b85") } >db.checkIfFieldIsNumberDemo.insertOne({"StudentId":101,"StudentName":"Larry","StudentCountryName":"AUS"}); { "acknowledged" : true, "insertedId" : ObjectId("5c9ec7ccd628fa4220163b86") }
以下是在find()
方法的帮助下显示集合中所有文档的查询
> db.checkIfFieldIsNumberDemo.find().pretty();
这将产生以下输出
{ "_id" : ObjectId("5c9ec75dd628fa4220163b83"), "StudentName" : "John", "StudentAge" : 23 } { "_id" : ObjectId("5c9ec77cd628fa4220163b84"), "StudentName" : "Chris", "StudentMathScore" : 98, "StudentCountryName" : "US" } { "_id" : ObjectId("5c9ec7a4d628fa4220163b85"), "StudentName" : "Robert", "StudentCountryName" : "AUS" } { "_id" : ObjectId("5c9ec7ccd628fa4220163b86"), "StudentId" : 101, "StudentName" : "Larry", "StudentCountryName" : "AUS" }
以下是检查字段是否为数字的查询
> db.checkIfFieldIsNumberDemo.find({StudentMathScore: {$type:"number"}}).pretty();
以下是显示字段的输出,该字段是一个数字,即StudentMathScore
{ "_id" : ObjectId("5c9ec77cd628fa4220163b84"), "StudentName" : "Chris", "StudentMathScore" : 98, "StudentCountryName" : "US" }