MongoDB 正则表达式用于获取名称为“John”,而不是“john”的特定记录
要搜索特定单词,请使用带有正则表达式的 /searchWord/。让我们创建一个包含文档的集合 −
> db.demo221.insertOne({"Details":{"StudentName":"Chris","StudentAge":21}}); { "acknowledged" : true, "insertedId" : ObjectId("5e3ee15d03d395bdc213472b") } > db.demo221.insertOne({"Details":{"StudentName":"John","StudentAge":20}}); { "acknowledged" : true, "insertedId" : ObjectId("5e3ee16503d395bdc213472c") } > db.demo221.insertOne({"Details":{"StudentName":"Bob","StudentAge":22}}); { "acknowledged" : true, "insertedId" : ObjectId("5e3ee16b03d395bdc213472d") } > db.demo221.insertOne({"Details":{"StudentName":"john","StudentAge":24}}); { "acknowledged" : true, "insertedId" : ObjectId("5e3ee17303d395bdc213472e") }
使用 find() 方法显示集合中的所有文档 −
> db.demo221.find();
这将产生以下输出 −
{ "_id" : ObjectId("5e3ee15d03d395bdc213472b"), "Details" : { "StudentName" : "Chris", "StudentAge" : 21 } } { "_id" : ObjectId("5e3ee16503d395bdc213472c"), "Details" : { "StudentName" : "John", "StudentAge" : 20 } } { "_id" : ObjectId("5e3ee16b03d395bdc213472d"), "Details" : { "StudentName" : "Bob", "StudentAge" : 22 } } { "_id" : ObjectId("5e3ee17303d395bdc213472e"), "Details" : { "StudentName" : "john", "StudentAge" : 24 } }
以下是使用名称“John”获取特定记录的查询 −
> db.demo221.find({"Details.StudentName":/John/});
这将产生以下输出 −
{ "_id" : ObjectId("5e3ee16503d395bdc213472c"), "Details" : { "StudentName" : "John", "StudentAge" : 20 } }
广告