Jan
Jan

Reputation: 3401

How to search for a specific pattern in MongoDB?

Im having trouble with my query in Meteor since I am not quite well versed with MongoDB.

This here is a sample collection with two documents.

Ducks: 
[{
   name: "duck1"
   metadata: {
       id: "id_1",
       category: "samecategory"
   }
},
{
   name: "daffy"
   metadata: {
       id: "id_2",
       category: "samecategory"
   }
}]

I implemented a search functionality from atmosphere. What I want to achieve is that when I search for example: d the results will be both ducks. du will be only be duck1 and naturally da will only be daffy. Also so that they will be filtered by the same category.

"$and": [{"name": {}}, {"metadata.category": "samecategory"}]

Inside the name {} is where the search queries. It will only give me the result when the name is exact. I can't find in the mongo docs if it has contains like in Java.

Upvotes: 1

Views: 433

Answers (1)

Matthias A. Eckhart
Matthias A. Eckhart

Reputation: 5156

The following query will return a subset of documents which names start with d and have metadata.category set to samecategory:

Ducks.find({"metadata.category": "samecategory", "name": /^d/});

The regular expression /^d/ is similar to LIKE 'd%'.

Upvotes: 1

Related Questions