要获取MySQL LIKE语句,请在MongoDB中使用REGEX。首先让我们创建一个包含文档的集合-
> db.likeInMongoDBDemo.insertOne({"Name" : "Sam"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd6922857806ebf1256f123") } > db.likeInMongoDBDemo.insertOne({"Name" : "John" }); { "acknowledged" : true, "insertedId" : ObjectId("5cd6923157806ebf1256f124") } > db.likeInMongoDBDemo.insertOne({"Name" : "Scott"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd6924557806ebf1256f125") } > db.likeInMongoDBDemo.insertOne({"Name" : "Sean"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd6924f57806ebf1256f126") } > db.likeInMongoDBDemo.insertOne({"Name" : "Samuel"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd6925857806ebf1256f127") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.likeInMongoDBDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cd6922857806ebf1256f123"), "Name" : "Sam" } { "_id" : ObjectId("5cd6923157806ebf1256f124"), "Name" : "John" } { "_id" : ObjectId("5cd6924557806ebf1256f125"), "Name" : "Scott" } { "_id" : ObjectId("5cd6924f57806ebf1256f126"), "Name" : "Sean" } { "_id" : ObjectId("5cd6925857806ebf1256f127"), "Name" : "Samuel" }
以下是执行REGEX以匹配MongoDB中的MySQL LIKE语句的查询-
> db.likeInMongoDBDemo.find({"Name":{$regex:"Sam"}});
这将产生以下输出-
{ "_id" : ObjectId("5cd6922857806ebf1256f123"), "Name" : "Sam" } { "_id" : ObjectId("5cd6925857806ebf1256f127"), "Name" : "Samuel" }