如何用“like”查询 MongoDB?


您可轻松使用“like”来查询 MongoDB

db.yourCollectionName.find({"yourFieldName" : /.*yourMatchingValue.*/}).pretty();

为了理解上述语法,让我们使用一些文档创建一个集合。此处,我们有一个名为“employee”的集合。查询如下:

> db.employee.insert({"EmployeeName":"John","EmployeeSalary":450000});
WriteResult({ "nInserted" : 1 })
> db.employee.insert({"EmployeeName":"Carol","EmployeeSalary":150000});
WriteResult({ "nInserted" : 1 })
> db.employee.insert({"EmployeeName":"James","EmployeeSalary":550000});
WriteResult({ "nInserted" : 1 })
> db.employee.insert({"EmployeeName":"Jace","EmployeeSalary":670000});
WriteResult({ "nInserted" : 1 })
> db.employee.insert({"EmployeeName":"Larry","EmployeeSalary":1000000});
WriteResult({ "nInserted" : 1 })

现在,您可以使用 find() 方法显示集合中的所有文档。查询如下:

> db.employee.find().pretty();

输出如下:

{
   "_id" : ObjectId("5c6c0b2e68174aae23f5ef59"),
   "EmployeeName" : "John",
   "EmployeeSalary" : 450000
}
{
   "_id" : ObjectId("5c6c0b3b68174aae23f5ef5a"),
   "EmployeeName" : "Carol",
   "EmployeeSalary" : 150000
}
{
   "_id" : ObjectId("5c6c0b4768174aae23f5ef5b"),
   "EmployeeName" : "James",
   "EmployeeSalary" : 550000
}
{
   "_id" : ObjectId("5c6c0b8f68174aae23f5ef5c"),
   "EmployeeName" : "Jace",
   "EmployeeSalary" : 670000
}
{
   "_id" : ObjectId("5c6c0b9e68174aae23f5ef5d"),
   "EmployeeName" : "Larry",
   "EmployeeSalary" : 1000000
}

以下是 MongoDB 中带有“like”操作符的查询:

> db.employee.find({"EmployeeName":/.*J.*/}).pretty();

输出如下:

{
   "_id" : ObjectId("5c6c0b2e68174aae23f5ef59"),
   "EmployeeName" : "John",
   "EmployeeSalary" : 450000
}
{
   "_id" : ObjectId("5c6c0b4768174aae23f5ef5b"),
   "EmployeeName" : "James",
   "EmployeeSalary" : 550000
}
{
   "_id" : ObjectId("5c6c0b8f68174aae23f5ef5c"),
   "EmployeeName" : "Jace",
   "EmployeeSalary" : 670000
}

更新日期:2019-07-30

2K+ 次浏览

开启你的职业

完成课程,获得认证

开始
广告