Monta
Monta

Reputation: 1180

Mongodb - Use a regex search to match embedded documents

I have a Mongo Collection :

db.sCriteria.insert({criteria : {a:"1",b:"2",c:"3"}})
db.sCriteria.insert({criteria : {a:"1",d:"2",e:"3"}})

The properties of the embedded document "criteria" can vary a lot so I chose to index the whole object :

db.sCriteria.ensureIndex({criteria : 1})

And my queries are always against the entire object to use the index. Ex :

db.sCriteria.find({criteria : {a:"1",b:"2",c:"3"}}).count() 
1
db.sCriteria.find({criteria : {a:"1",b:"2"}}).count() 
0

What I want to be able to do is to use regex for some property. For example :

db.sCriteria.find({criteria : {a:"1",b:"2",c:/3/}}).count() 

This always gives 0 results

Is there a way to do this and use the index?

Upvotes: 0

Views: 358

Answers (1)

Sede
Sede

Reputation: 61273

Your query may not return any document if what you are querying is subdocument because the field order matter.The best thing to do is to create a coumpound indexes and use the dot notation.

db.sCriteria.count({ "criteria.a": "1", "criteria.b": "2", "criteria.c": /3/})

Upvotes: 2

Related Questions