如何在 MongoDB 中检查字段是否为数字?

mongodbdatabasebig data analytics

要在 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"
}

相关文章