在MongoDB中使用LIKE查找匹配记录?
首先让我们创建一个包含文档的集合-
> db.likeDemo.insertOne({"Name":"John",Age:32}); { "acknowledged" : true, "insertedId" : ObjectId("5cb84984623186894665ae41") } > db.likeDemo.insertOne({"Name":"Chris",Age:25}); { "acknowledged" : true, "insertedId" : ObjectId("5cb84991623186894665ae42") } > db.likeDemo.insertOne({"Name":"Carol",Age:22}); { "acknowledged" : true, "insertedId" : ObjectId("5cb849a1623186894665ae43") } > db.likeDemo.insertOne({"Name":"Johnny",Age:22}); { "acknowledged" : true, "insertedId" : ObjectId("5cb849b2623186894665ae44") } > db.likeDemo.insertOne({"Name":"James",Age:27}); { "acknowledged" : true, "insertedId" : ObjectId("5cb849bb623186894665ae45") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.likeDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cb84984623186894665ae41"), "Name" : "John", "Age" : 32 } { "_id" : ObjectId("5cb84991623186894665ae42"), "Name" : "Chris", "Age" : 25 } { "_id" : ObjectId("5cb849a1623186894665ae43"), "Name" : "Carol", "Age" : 22 } { "_id" : ObjectId("5cb849b2623186894665ae44"), "Name" : "Johnny", "Age" : 22 } { "_id" : ObjectId("5cb849bb623186894665ae45"), "Name" : "James", "Age" : 27 }
以下是MongoDB中的LIKE查询,显示以名称“Jo”开头的记录-
> db.likeDemo.find({Name: /^Jo/i } ).pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cb84984623186894665ae41"), "Name" : "John", "Age" : 32 } { "_id" : ObjectId("5cb849b2623186894665ae44"), "Name" : "Johnny", "Age" : 22 }