如何查询类似于“ like”的MongoDB?
要实现类似于“like”的功能,请find()
在MongoDB中与//一起使用。让我们创建一个包含文档的集合-
> db.demo686.insertOne({"FirstName":"Robert"}); { "acknowledged" : true, "insertedId" : ObjectId("5ea55182a7e81adc6a0b395c") } > db.demo686.insertOne({"FirstName":"John"}); { "acknowledged" : true, "insertedId" : ObjectId("5ea55186a7e81adc6a0b395d") } > db.demo686.insertOne({"FirstName":"ROBERT"}); { "acknowledged" : true, "insertedId" : ObjectId("5ea5518fa7e81adc6a0b395e") } > db.demo686.insertOne({"FirstName":"David"}); { "acknowledged" : true, "insertedId" : ObjectId("5ea55195a7e81adc6a0b395f") } > db.demo686.insertOne({"FirstName":"robert"}); { "acknowledged" : true, "insertedId" : ObjectId("5ea5519ba7e81adc6a0b3960") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo686.find();
这将产生以下输出-
{ "_id" : ObjectId("5ea55182a7e81adc6a0b395c"), "FirstName" : "Robert" } { "_id" : ObjectId("5ea55186a7e81adc6a0b395d"), "FirstName" : "John" } { "_id" : ObjectId("5ea5518fa7e81adc6a0b395e"), "FirstName" : "ROBERT" } { "_id" : ObjectId("5ea55195a7e81adc6a0b395f"), "FirstName" : "David" } { "_id" : ObjectId("5ea5519ba7e81adc6a0b3960"), "FirstName" : "robert" }
以下是类似于“like”的查询-
> db.demo686.find({FirstName:/Robert/i});
这将产生以下输出-
{ "_id" : ObjectId("5ea55182a7e81adc6a0b395c"), "FirstName" : "Robert" } { "_id" : ObjectId("5ea5518fa7e81adc6a0b395e"), "FirstName" : "ROBERT" } { "_id" : ObjectId("5ea5519ba7e81adc6a0b3960"), "FirstName" : "robert" }