使用長度標準查詢 MongoDB?
要使用長度標準查詢 MongoDB,可以使用正則表示式。以下是語法
db.yourCollectionName.find({ ‘yourFieldName’: { $regex: /^.{yourLengthValue1,yourLengthValue2}$/ } });讓我們建立一個包含文件的集合。以下是該查詢
> db.queryLengthDemo.insertOne({"StudentFullName":"John Smith"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9a01ae353decbc2fc927c0")
}
> db.queryLengthDemo.insertOne({"StudentFullName":"John Doe"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9a01b4353decbc2fc927c1")
}
> db.queryLengthDemo.insertOne({"StudentFullName":"David Miller"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9a01c2353decbc2fc927c2")
}
> db.queryLengthDemo.insertOne({"StudentFullName":"Robert Taylor"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9a01e2353decbc2fc927c3")
}
> db.queryLengthDemo.insertOne({"StudentFullName":"Chris Williams"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9a01f1353decbc2fc927c4")
}以下是使用 find() 方法顯示集合中所有文件的查詢
> db.queryLengthDemo.find().pretty();
這將產生以下輸出
{
"_id" : ObjectId("5c9a01ae353decbc2fc927c0"),
"StudentFullName" : "John Smith"
}
{
"_id" : ObjectId("5c9a01b4353decbc2fc927c1"),
"StudentFullName" : "John Doe"
}
{
"_id" : ObjectId("5c9a01c2353decbc2fc927c2"),
"StudentFullName" : "David Miller"
}
{
"_id" : ObjectId("5c9a01e2353decbc2fc927c3"),
"StudentFullName" : "Robert Taylor"
}
{
"_id" : ObjectId("5c9a01f1353decbc2fc927c4"),
"StudentFullName" : "Chris Williams"
}以下是使用長度標準的 MongoDB 查詢
> db.queryLengthDemo.find({ StudentFullName: { $regex: /^.{9,12}$/ } }).pretty();這將產生以下輸出
{
"_id" : ObjectId("5c9a01ae353decbc2fc927c0"),
"StudentFullName" : "John Smith"
}
{
"_id" : ObjectId("5c9a01c2353decbc2fc927c2"),
"StudentFullName" : "David Miller"
}
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP