MongoDB 正则表达式搜索整数值?
若要对整数值执行正则表达式搜索,您需要使用 $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() 方法显示所有文档。查询如下
> 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 }
广告