你可以使用以下方法在MongoDB中用 "like "regex执行查询。
方法1:查找包含字符串的文档
db.collection.find({name: {$regex : /string/i}})
注意,i表示不区分大小写的匹配。
方法2:查找以字符串开始的文件
db.collection.find({name: {$regex : /^string/i}})
方法3:查找以字符串结尾的文档
db.collection.find({name: {$regex : /string$/i}})
下面的例子显示了如何在一个有以下文档的集合队中使用每种方法。
db.teams.insertOne({team: "Mavs", position: "Guard", points: 31})
例1:查找包含字符串的文档
我们可以使用下面的代码来查找所有在团队字段中包含 "avs "字符串的文档。
db.teams.find({team: {$regex : /avs/i}})
这个查询返回以下两个文档。
{ _id: ObjectId("618050098ffcfe76d07b1da5"),
team: 'Mavs',
position: 'Guard',
points: 31 }
{ _id: ObjectId("618285361a42e92ac9ccd2c6"),
team: 'Cavs',
position: 'Guard',
points: 33 }
例2:查找以字符串开头的文档
我们可以用下面的代码找到所有在position字段中以字符串'gua'开头的文档。
db.teams.find({position: {$regex : /^gua/i}})
这个查询返回以下三个文档。
{ _id: ObjectId("618050098ffcfe76d07b1da5"),
team: 'Mavs',
position: 'Guard',
points: 31 }
{ _id: ObjectId("6180504e8ffcfe76d07b1da7"),
team: 'Spurs',
position: 'Guard',
points: 22 }
{ _id: ObjectId("618285361a42e92ac9ccd2c6"),
team: 'Cavs',
position: 'Guard',
points: 33 }
例3:查找以字符串结尾的文档
我们可以使用下面的代码来查找所有在position字段中以'ward'结尾的文档。
db.teams.find({position: {$regex : /ward$/i}})
这个查询返回以下文档。
{ _id: ObjectId("618050808ffcfe76d07b1dab"),
team: 'Warriors',
position: 'Forward',
points: 26 }
注意:你可以在这里找到**$regex**的完整文档。
The postMongoDB: How to Query with "Like" Regexappeared first onStatology.