Fuzzy query is one of the basic operations of the database. The following article mainly introduces the method tutorial of using Node.js to implement fuzzy query on the MongoDB database. The article gives The detailed introduction and sample code are given, which has certain reference value for everyone. Friends who need it can take a look below.
Preface
Fuzzy query is one of the basic operations of the database. It checks whether a given string matches the Match the specified pattern. If the characters match completely, it can be expressed by = equal sign. If the characters match partially, it can be considered as a fuzzy query. In relational data, use syntax like ‘%fens%’ via SQL. So how should we achieve the effect of fuzzy query in mongodb.
Directory
mongodb fuzzy query
nodejs through mongoose Fuzzy query
1. Mongodb fuzzy query
We open mongodb and test with the name text field .
Exact Query
When {'name':'Future Police'}, a record is accurately matched.
db.movies.find({'name':'未来警察'})
Fuzzy query
{'name':/future/}, multiple records were matched.
db.movies.find({'name':/未来/})
MongoDB’s fuzzy query is actually a type of regular query.
Note: In relational data, there is a separate keyword like for fuzzy query. If you do not use like, you can also use regular query in relational data.
MongoDB official introduction: docs.mongodb.org/manual/reference/operator/regex/
Official example:
db.collection.find( { field: /acme.*corp/i } ); db.collection.find( { field: { $regex: 'acme.*corp', $options: 'i' } } );
2. Nodejs uses fuzzy query of mongoose
The desired effect:
The following is said Talk about how to use mongoose for fuzzy query.
Using mongoose to access mongodb has been discussed in the article Using Mongoose to directly insert JSON data or update to MongoDB.
We model the Movie and construct the dao layer.
Query all movies
MovieDAO.prototype.findByName = function(query, callback) { Movie.findOne(query, function(err, obj){ callback(err, obj); }); };
You can query by passing in queryobject.
Next, construct the query object
//代码片断 exports.movie = function(req, res) { var query={}; if(req.query.m2) { query['name']=new RegExp(req.query.m2);//模糊查询参数 } Movie.findByName (query,function(err, list){ return res.render('admin/movie', {movieList:list}); }); }
Please note:We have just analyzed MongoDB’s fuzzy query through regular Expression is implemented, corresponding to mongodb, you can directly use the '/../' slash.
But in nodejs, you must use RegExp to build a regular expression object.
The above is the detailed content of Tutorial on how to implement fuzzy query on MongoDB using js. For more information, please follow other related articles on the PHP Chinese website!