Computer >> Máy Tính >  >> Lập trình >> MongoDB

Làm cách nào để kiểm tra xem trường có phải là một số trong MongoDB không?

Để kiểm tra xem trường có phải là một số trong MongoDB hay không, hãy sử dụng toán tử $ type. Sau đây là cú pháp

db.yourCollectionName.find({youtFieldName: {$type:"number"}}).pretty();

Trước tiên, hãy để chúng tôi tạo một bộ sưu tập với các tài liệu

> 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")
}

Sau đây là truy vấn để hiển thị tất cả các tài liệu từ một bộ sưu tập với sự trợ giúp của phương thức find ()

> db.checkIfFieldIsNumberDemo.find().pretty();

Điều này sẽ tạo ra kết quả sau

{
   "_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"
}

Sau đây là truy vấn để kiểm tra xem một trường có phải là một số hay không

> db.checkIfFieldIsNumberDemo.find({StudentMathScore: {$type:"number"}}).pretty();

Sau đây là đầu ra hiển thị trường là một số, tức là StudentMathScore

{
   "_id" : ObjectId("5c9ec77cd628fa4220163b84"),
   "StudentName" : "Chris",
   "StudentMathScore" : 98,
   "StudentCountryName" : "US"
}