如何用“ 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

}

以上是 如何用“ like”查询MongoDB? 的全部内容, 来源链接: utcz.com/z/338301.html

回到顶部