wazzaday
wazzaday

Reputation: 9664

searching an array of values with mongoDB

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?

Upvotes: 0

Views: 78

Answers (1)

user2941651
user2941651

Reputation:

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.

Upvotes: 1

Related Questions