在 MongoDB 中检查一个字段是否包含一个字符串?
你可以在 MongoDB 中使用 $regex 运算符来检查一个字段是否包含一个字符串。语法如下 −
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() 方法显示集合中的所有文档。查询如下 −
> 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" }
广告