在MongoDB文档中搜索带有特殊字符的字符串?
要在MongoDB文档中搜索带有特殊字符的字符串,可以使用\。在这里,我们在字符串中有特殊字符$。
让我们首先实现以下查询以创建包含文档的集合
>db.searchDocumentWithSpecialCharactersDemo.insertOne({"UserId":"Smith$John123","UserFirstName":"John","UserLastName":"Smith"}); { "acknowledged" : true, "insertedId" : ObjectId("5c987b98330fd0aa0d2fe4b1") } >db.searchDocumentWithSpecialCharactersDemo.insertOne({"UserId":"Taylor$Carol983","UserFirstName":"Carol","UserLastName":"Taylor"}); { "acknowledged" : true, "insertedId" : ObjectId("5c987bdb330fd0aa0d2fe4b2") } >db.searchDocumentWithSpecialCharactersDemo.insertOne({"UserId":"Doe$John999","UserFirstName":"John","UserLastName":"Doe"}); { "acknowledged" : true, "insertedId" : ObjectId("5c987bee330fd0aa0d2fe4b3") } >db.searchDocumentWithSpecialCharactersDemo.insertOne({"UserId":"Miller$David555","UserFirstName":"David","UserLastName":"Miller"}); { "acknowledged" : true, "insertedId" : ObjectId("5c987c01330fd0aa0d2fe4b4") }
以下是在find()
方法的帮助下显示集合中所有文档的查询
> db.searchDocumentWithSpecialCharactersDemo.find().pretty();
这将产生以下输出
{ "_id" : ObjectId("5c987b98330fd0aa0d2fe4b1"), "UserId" : "Smith$John123", "UserFirstName" : "John", "UserLastName" : "Smith" } { "_id" : ObjectId("5c987bdb330fd0aa0d2fe4b2"), "UserId" : "Taylor$Carol983", "UserFirstName" : "Carol", "UserLastName" : "Taylor" } { "_id" : ObjectId("5c987bee330fd0aa0d2fe4b3"), "UserId" : "Doe$John999", "UserFirstName" : "John", "UserLastName" : "Doe" } { "_id" : ObjectId("5c987c01330fd0aa0d2fe4b4"), "UserId" : "Miller$David555", "UserFirstName" : "David", "UserLastName" : "Miller" }
以下是在MongoDB文档中搜索带有特殊字符的字符串的查询。在这里,我们正在搜索带有特殊字符$的字符串John。
> db.searchDocumentWithSpecialCharactersDemo.find({ UserId : /.*\$John.*/i }).pretty();
这将产生以下输出:
{ "_id" : ObjectId("5c987b98330fd0aa0d2fe4b1"), "UserId" : "Smith$John123", "UserFirstName" : "John", "UserLastName" : "Smith" } { "_id" : ObjectId("5c987bee330fd0aa0d2fe4b3"), "UserId" : "Doe$John999", "UserFirstName" : "John", "UserLastName" : "Doe" }