您可以使用“ $regex”运算符在MongoDB中实现与SQL“ like”等效的功能。为了实现它,让我们创建一个带有文档的集合。使用文档创建集合的查询如下-
> db.sqlLikeDemo.insertOne({"UserName":"John Smith","UserAge":24}); { "acknowledged" : true, "insertedId" : ObjectId("5c912e124afe5c1d2279d6a5") } > db.sqlLikeDemo.insertOne({"UserName":"John Doe","UserAge":21}); { "acknowledged" : true, "insertedId" : ObjectId("5c912e264afe5c1d2279d6a6") } > db.sqlLikeDemo.insertOne({"UserName":"Chris Williams","UserAge":22}); { "acknowledged" : true, "insertedId" : ObjectId("5c912e404afe5c1d2279d6a7") } > db.sqlLikeDemo.insertOne({"UserName":"Robert Taylor","UserAge":26}); { "acknowledged" : true, "insertedId" : ObjectId("5c912e4d4afe5c1d2279d6a8") } > db.sqlLikeDemo.insertOne({"UserName":"John Brown","UserAge":27}); { "acknowledged" : true, "insertedId" : ObjectId("5c912e6c4afe5c1d2279d6a9") } > db.sqlLikeDemo.insertOne({"UserName":"Mike Brown","UserAge":23}); { "acknowledged" : true, "insertedId" : ObjectId("5c912e794afe5c1d2279d6aa") } > db.sqlLikeDemo.insertOne({"UserName":"Larry Smith","UserAge":24}); { "acknowledged" : true, "insertedId" : ObjectId("5c912e8c4afe5c1d2279d6ab") }
在find()
method的帮助下显示集合中的所有文档。查询如下-
> db.sqlLikeDemo.find().pretty();
以下是输出-
{ "_id" : ObjectId("5c912e124afe5c1d2279d6a5"), "UserName" : "John Smith", "UserAge" : 24 } { "_id" : ObjectId("5c912e264afe5c1d2279d6a6"), "UserName" : "John Doe", "UserAge" : 21 } { "_id" : ObjectId("5c912e404afe5c1d2279d6a7"), "UserName" : "Chris Williams", "UserAge" : 22 } { "_id" : ObjectId("5c912e4d4afe5c1d2279d6a8"), "UserName" : "Robert Taylor", "UserAge" : 26 } { "_id" : ObjectId("5c912e6c4afe5c1d2279d6a9"), "UserName" : "John Brown", "UserAge" : 27 } { "_id" : ObjectId("5c912e794afe5c1d2279d6aa"), "UserName" : "Mike Brown", "UserAge" : 23 } { "_id" : ObjectId("5c912e8c4afe5c1d2279d6ab"), "UserName" : "Larry Smith", "UserAge" : 24 }
这是类似于SQL'like'子句的查询,即带有“ UserName” John的记录-
> db.sqlLikeDemo.find({"UserName":{"$regex": "John"}}).pretty();
以下是输出-
{ "_id" : ObjectId("5c912e124afe5c1d2279d6a5"), "UserName" : "John Smith", "UserAge" : 24 } { "_id" : ObjectId("5c912e264afe5c1d2279d6a6"), "UserName" : "John Doe", "UserAge" : 21 } { "_id" : ObjectId("5c912e6c4afe5c1d2279d6a9"), "UserName" : "John Brown", "UserAge" : 27 }