MongoDB正则表达式显示前五个字母大写的记录?
首先让我们创建一个包含文档的集合-
> db.upperCaseFiveLetterDemo.insertOne({"StudentFullName":"JOHN Smith"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd7edef1a844af18acdffb2") } > db.upperCaseFiveLetterDemo.insertOne({"StudentFullName":"SAM Williams"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd7ee011a844af18acdffb3") } > db.upperCaseFiveLetterDemo.insertOne({"StudentFullName":"CAROL Taylor"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd7ee101a844af18acdffb4") } > db.upperCaseFiveLetterDemo.insertOne({"StudentFullName":"Bob Taylor"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd7ee351a844af18acdffb5") } > db.upperCaseFiveLetterDemo.insertOne({"StudentFullName":"DAVID Miller"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd7ee451a844af18acdffb6") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.upperCaseFiveLetterDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cd7edef1a844af18acdffb2"), "StudentFullName" : "JOHN Smith" } { "_id" : ObjectId("5cd7ee011a844af18acdffb3"), "StudentFullName" : "SAM Williams" } { "_id" : ObjectId("5cd7ee101a844af18acdffb4"), "StudentFullName" : "CAROL Taylor" } { "_id" : ObjectId("5cd7ee351a844af18acdffb5"), "StudentFullName" : "Bob Taylor" } { "_id" : ObjectId("5cd7ee451a844af18acdffb6"), "StudentFullName" : "DAVID Miller" }
以下是查询以获取前五个字母大写的记录数-
> db.upperCaseFiveLetterDemo.find({StudentFullName : {$regex : /[A-Z]{5}/ } }).count();
这将产生以下输出-
2
有两个文档,前五个字母大写。现在让我们显示这些文档-
> db.upperCaseFiveLetterDemo.find({StudentFullName : {$regex : /[A-Z]{5}/ } });
这将产生以下输出-
{ "_id" : ObjectId("5cd7ee101a844af18acdffb4"), "StudentFullName" : "CAROL Taylor" } { "_id" : ObjectId("5cd7ee451a844af18acdffb6"), "StudentFullName" : "DAVID Miller" }