0

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?

1 Answer 1

2

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/})
Sign up to request clarification or add additional context in comments.

3 Comments

In this case my index will not be used. And I can't create an index for each property because in reality I have other properties with which I index the criteria object, which will make it very complex
you don't need to index every fields in your subdocument absolutely not. you can use compound indexes
The index I described is only used to find the whole object. It's not used with your proposition

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.