正则表达式忽略MongoDB中的特定字符?
您可以将正则表达式与$not运算符一起使用,以忽略特定字符并显示其余字符。首先让我们创建一个包含文档的集合-
> db.regexDemo.insertOne({"CustomerId":"Customer#1234","CustomerName":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5cc7428f8f9e6ff3eb0ce436") } > db.regexDemo.insertOne({"CustomerId":"Customer5678","CustomerName":"Robert"}); { "acknowledged" : true, "insertedId" : ObjectId("5cc7429e8f9e6ff3eb0ce437") } > db.regexDemo.insertOne({"CustomerId":"Customer#777","CustomerName":"Carol"}); { "acknowledged" : true, "insertedId" : ObjectId("5cc742ae8f9e6ff3eb0ce438") } > db.regexDemo.insertOne({"CustomerId":"Customer777","CustomerName":"David"}); { "acknowledged" : true, "insertedId" : ObjectId("5cc742bc8f9e6ff3eb0ce439") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.regexDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cc7428f8f9e6ff3eb0ce436"), "CustomerId" : "Customer#1234", "CustomerName" : "Chris" } { "_id" : ObjectId("5cc7429e8f9e6ff3eb0ce437"), "CustomerId" : "Customer5678", "CustomerName" : "Robert" } { "_id" : ObjectId("5cc742ae8f9e6ff3eb0ce438"), "CustomerId" : "Customer#777", "CustomerName" : "Carol" } { "_id" : ObjectId("5cc742bc8f9e6ff3eb0ce439"), "CustomerId" : "Customer777", "CustomerName" : "David" }
情况1-这是避免在MongoDB中使用特定字符的查询。字符是#-
> db.regexDemo.find({CustomerId: /^[^#]*$/}).pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cc7429e8f9e6ff3eb0ce437"), "CustomerId" : "Customer5678", "CustomerName" : "Robert" } { "_id" : ObjectId("5cc742bc8f9e6ff3eb0ce439"), "CustomerId" : "Customer777", "CustomerName" : "David" }
情况2–这是另一个查询,以避免在MongoDB中使用特定字符。字符是#-
> db.regexDemo.find({CustomerId: {$not: /#/}}).pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cc7429e8f9e6ff3eb0ce437"), "CustomerId" : "Customer5678", "CustomerName" : "Robert" } { "_id" : ObjectId("5cc742bc8f9e6ff3eb0ce439"), "CustomerId" : "Customer777", "CustomerName" : "David" }