查询 MongoDB,使用“like”实现基于以特定字母开头的姓名和电子邮件字段?
如需在 MongoDB 中实现“like”,请使用 / /,并在两者之间设置特定字母。例如,−
/J/
让我们创建一个带有文档的集合 −
> db.demo554.insertOne({"UserName":"John","UserMailId":"[email protected]"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8f1cfed1d72c4545cb8679") } > db.demo554.insertOne({"UserName":"Chris","UserMailId":"[email protected]"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8f1d0cd1d72c4545cb867a") } > db.demo554.insertOne({"UserName":"Jace","UserMailId":"[email protected]"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8f1d1cd1d72c4545cb867b") }
使用 find() 方法显示集合中的所有文档−
> db.demo554.find();
将会生成以下输出 −
{ "_id" : ObjectId("5e8f1cfed1d72c4545cb8679"), "UserName" : "John", "UserMailId" : "[email protected]" } { "_id" : ObjectId("5e8f1d0cd1d72c4545cb867a"), "UserName" : "Chris", "UserMailId" : "[email protected]" } { "_id" : ObjectId("5e8f1d1cd1d72c4545cb867b"), "UserName" : "Jace", "UserMailId" : "[email protected]" }
以下是对“like”的实现查询−
> db.demo554.find({ ... "$or": [ ... { "UserName": /J/ }, ... ... { "UserMailId": /J/ } ... ] ... } ... );
将会生成以下输出 −
{ "_id" : ObjectId("5e8f1cfed1d72c4545cb8679"), "UserName" : "John", "UserMailId" : "[email protected]" } { "_id" : ObjectId("5e8f1d1cd1d72c4545cb867b"), "UserName" : "Jace", "UserMailId" : "[email protected]" }
广告