要对整数值执行正则表达式搜索,您需要使用$where运算符。语法如下:
db.yourCollectionName.find({ $where: "/^yourIntegerPatternValue.*/.test(this.yourFieldName)" });
为了理解上述概念,让我们创建一个带有文档的集合。用于创建包含文档的集合的查询如下:
> db.regExpOnIntegerDemo.insertOne({"StudentId":2341234}); { "acknowledged" : true, "insertedId" : ObjectId("5c70370c75eb1743ddddce21") } > db.regExpOnIntegerDemo.insertOne({"StudentId":123234}); { "acknowledged" : true, "insertedId" : ObjectId("5c70371175eb1743ddddce22") } > db.regExpOnIntegerDemo.insertOne({"StudentId":9871234}); { "acknowledged" : true, "insertedId" : ObjectId("5c70371875eb1743ddddce23") } > db.regExpOnIntegerDemo.insertOne({"StudentId":2345612}); { "acknowledged" : true, "insertedId" : ObjectId("5c70372275eb1743ddddce24") } > db.regExpOnIntegerDemo.insertOne({"StudentId":1239812345}); { "acknowledged" : true, "insertedId" : ObjectId("5c70372975eb1743ddddce25") }
在find()
method的帮助下显示集合中的所有文档。查询如下:
> db.regExpOnIntegerDemo.find().pretty();
以下是输出:
{ "_id" : ObjectId("5c70370c75eb1743ddddce21"), "StudentId" : 2341234 } { "_id" : ObjectId("5c70371175eb1743ddddce22"), "StudentId" : 123234 } { "_id" : ObjectId("5c70371875eb1743ddddce23"), "StudentId" : 9871234 } { "_id" : ObjectId("5c70372275eb1743ddddce24"), "StudentId" : 2345612 } { "_id" : ObjectId("5c70372975eb1743ddddce25"), "StudentId" : 1239812345 }
这是对整数值进行正则表达式搜索的查询:
> db.regExpOnIntegerDemo.find({ $where: "/^123.*/.test(this.StudentId)" });
以下是输出:
{ "_id" : ObjectId("5c70371175eb1743ddddce22"), "StudentId" : 123234 } { "_id" : ObjectId("5c70372975eb1743ddddce25"), "StudentId" : 1239812345 }