Reputation: 1149
I'm new to mongodb and mongoose and I'm trying to figure out how to do a query that let's me find all records/documents where a field contains a particular string. This is for use with a search feature. For example, if I have a "users" collection, then I want to find all users whose firstname begins with, say, the string "Jo". Like this:
var Users = require('./models/users');
Users.find({ firstname : contains the string 'Jo' }, function(err, user) {
if (err) {
return done(err);
} else {
return res.json({
firstname: user.firstname,
});
}
});
I'm not sure what to put in place of "contains the string 'Jo'" so that this query will work. Basically, it should return records/documents such as "Joe", "John", "Joyce", etc.
UPDATE===========================================
Here is the updated code, but it returns all records, instead of only returning the ones that match "str":
app.get('/search/:str', function(req, res) {
var Users = require('./models/users');
Users.find({name: /[req.params.str]/}, function(err, data) {
if (err) return console.error(err);
return res.json(data);
})
});
The problem is with /[req.params.str]/
. If str
is set to "Jo", then it should only return users whose name contains the string "Jo", but it is returning every record. How can I fix this?
Upvotes: 1
Views: 6578
Reputation: 4173
2 ways to do this:
With regular expression. MongoDB supports regular expression match. here's an example:
users.find({firstname: /Jo/}, function(err, doc) {...})
However, if you got a big collection, it's going to be slow. Because regular expression usually doesn't use index at all unless you have a fixed prefix like /^Jo/.
Or in some situations you may want to try the new feature, full text search: First of all, you need an text index:
db.users.ensureIndex( { firstname: "text" } );
Then use the $text operator:
db.users.find({ $text: { $search: "Jo"}});
The text search does not just look for exactly what you are searching. And in some situations it may not work the way you wanted.
The $text operator can search for words and phrases. The query matches on the complete stemmed words. For example, if a document field contains the word blueberry, a search on the term blue will not match the document.
More information, please refer to the document.
Upvotes: 4