MongoDB multi condition fuzzy query sample code
- 2020-12-18 01:58:43
- OfStack
preface
A fuzzy query is one of the basic operations of a database that implements whether a given string matches a specified pattern. If the characters match exactly, it can be represented by the = equals sign, and if the match is partial, it can be considered a fuzzy query. In relational data, the syntax of like '%fens%' is used through SQL. So how do we achieve the effect of fuzzy queries in mongodb?
Query conditions
关键字 | 说明 |
---|---|
$or | 或关系 |
$nor | 或关系取反 |
$gt | 大于 |
$gte | 大于等于 |
$lt | 小于 |
$lte | 小于等于 |
$ne | 不等于 |
$in | 在多个值范围内 |
$nin | 不在多个值范围内 |
$all | 匹配数组中多个值 |
$regex | 正则,用于模糊查询 |
$size | 匹配数组大小 |
$maxDistance | 范围查询,距离(基于LBS) |
$mod | 取模运算 |
$near | 邻域查询,查询附近的位置(基于LBS) |
$exists | 字段是否存在 |
$elemMatch | 匹配内数组内的元素 |
$within | 范围查询(基于LBS) |
$box | 范围查询,矩形范围 |
$center | 范围查询,圆形范围 |
$centerSphere | 范围查询,球形范围 |
$slice | 查询字段集合中的元素(比如从第几个之后,第N到第M个元素) |
Fuzzy query
Precise query
//Mongodb The database table
const systemUser = require('../../models/user');
systemUser.find({name:'xiaoming'}).exec(function(err,rs){}
Multi-condition fuzzy query
//Mongodb The database table
const systemUser = require('../../models/user');
// The key to query passed in from the front end
var name = req.query.name;
var page = req.query.page || 1; // The current number of pages
var limitNums = 10; // Specify each 1 The number of entries in the page query
page = parseInt(page);
var skipNums = (page - 1) * limitNums; // Skip the specified number
// Regular match i Ignore case
var reg = new RegExp(name, "i");
var _filter = {
// Multi-field matching
$or: [
{name: {$regex: reg}},
{description: {$regex: reg}},
{owner: {$regex: reg}},
]
}
systemUser.find(_filter).
// Skip the specified amount of data
skip(skipNums).
// Specify the from MongoDB Number of records read in.
limit(limitNums).
sort({createTime:-1}).
exec(function(err,rs){}
conclusion