如何检查 MongoDB 中的字段是否为数字?
要检查 MongoDB 中的字段是否为数字,请使用 $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" }
广告