0

I have a collection which contains only 1 document:

events: ['some event', 'another one', 'and another'];

how can I perform a search against this so if the search parameter was "som", the docs returned would be "some event".

Currently I have the following:

var collection = db.collection('suggestions');
collection.ensureIndex({events: "text"}, function(){});

collection.find({ $text: { $search: term } }).toArray(function(err, docs){
    if(err){
        console.log(err);
    }else{
        res.send(docs);
    }
});

where term is the search term - but this always returns an empty array [].

Can this be done with mongoDB?

1
  • $text is a full-text search. It searches over the tokens in your input text (with word stemming, so that {$text: {$search: 'events'}} would actually find something, even if the word your document actually contains is 'event'). It depends on the value of term and the value of default_language of the index (or $language parameter of the search) what the result will look like. Maybe you didn't actually want to use a $text search? Commented Jan 31, 2015 at 13:10

1 Answer 1

1

I think that searching a part of the word would require using regex queries, since text indexes, however very useful, as far as I know may only serve to find whole words.

You might find a part of the word using the following query :

var collection = db.collection('suggestions');
collection.ensureIndex({events: 1}, function(){});

var query = { events: new RegExp( term ) };

collection.find(query).toArray(function(err, docs){
    if(err){
        console.log(err);
    }else{
        res.send(docs);
    }
});

In the above there is also multi-key index created on events array (as an option for consideration).

I hope it helps at least slightly.

Sign up to request clarification or add additional context in comments.

2 Comments

'/' + term + '/' does not construct a regex.
new RegExp(term) is not safe, because term can contain special characters. The term must be quoted, see this answer. stackoverflow.com/a/2593661/18771

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.