您可以使用$regex运算符来检查字段是否在MongoDB中包含字符串。语法如下-
db.yourCollectionName.findOne({"yourFieldName":{$regex:".*yourValue.*"}});
为了理解上述概念,让我们用文档创建一个集合。使用文档创建集合的查询如下-
> db.checkFieldContainsStringDemo.insertOne({"Id":1,"Name":"John"}); { "acknowledged" : true, "insertedId" : ObjectId("5c77d762fc4e719b197a12ed") } > db.checkFieldContainsStringDemo.insertOne({"Id":2,"Name":"Johnson"}); { "acknowledged" : true, "insertedId" : ObjectId("5c77d76bfc4e719b197a12ee") } > db.checkFieldContainsStringDemo.insertOne({"Id":3,"Name":"Carol"}); { "acknowledged" : true, "insertedId" : ObjectId("5c77d774fc4e719b197a12ef") } > db.checkFieldContainsStringDemo.insertOne({"Id":4,"Name":"Mike"}); { "acknowledged" : true, "insertedId" : ObjectId("5c77d77cfc4e719b197a12f0") } > db.checkFieldContainsStringDemo.insertOne({"Id":5,"Name":"Sam"}); { "acknowledged" : true, "insertedId" : ObjectId("5c77d784fc4e719b197a12f1") } > db.checkFieldContainsStringDemo.insertOne({"Id":6,"Name":"Larry"}); { "acknowledged" : true, "insertedId" : ObjectId("5c77d78cfc4e719b197a12f2") }
在find()
method的帮助下显示集合中的所有文档。查询如下-
> db.checkFieldContainsStringDemo.find();
以下是输出-
{ "_id" : ObjectId("5c77d762fc4e719b197a12ed"), "Id" : 1, "Name" : "John" } { "_id" : ObjectId("5c77d76bfc4e719b197a12ee"), "Id" : 2, "Name" : "Johnson" } { "_id" : ObjectId("5c77d774fc4e719b197a12ef"), "Id" : 3, "Name" : "Carol" } { "_id" : ObjectId("5c77d77cfc4e719b197a12f0"), "Id" : 4, "Name" : "Mike" } { "_id" : ObjectId("5c77d784fc4e719b197a12f1"), "Id" : 5, "Name" : "Sam" } { "_id" : ObjectId("5c77d78cfc4e719b197a12f2"), "Id" : 6, "Name" : "Larry" }
这是检查该字段是否包含MongoDB中特定字符串的查询。这里我们在字段中搜索的字符串是“ Johnson”-
> db.checkFieldContainsStringDemo.findOne({"Name":{$regex:".*Johnson.*"}});
以下是输出-
{ "_id" : ObjectId("5c77d76bfc4e719b197a12ee"), "Id" : 2, "Name" : "Johnson" }