John Prawyn
John Prawyn

Reputation: 1673

How to use $regex in projection

My mongodb document looks like this,

{'finance_pl': 
    {'S': 
        {
         '** 200903': {'reported_eps': '19.48'}, 
         '200806':  {'reported_eps': '18.8'}
        }
    }
}

** 200903 ==> year 2009 month 03.

Simple way to fetch reported_eps is this

db.collection.find(
    {}, 
    {'finance_pl.S.200803.reported_eps':1}
)

but the problem is i only have the year 2008 or 2009 the month part need to generate dynamically.

I need something like this

db.collection.find(
    {}, 
    {'finance_pl.S.2008[0-9]{2}.reported_eps':1}
)

[0-9]{2} --> python regex, to match two digits.

All the example I found in the documentation and in other places have not used $regex in projection part.

I am using pymongo. How should I solve this.

Upvotes: 1

Views: 728

Answers (1)

Sammaye
Sammaye

Reputation: 43884

You cannot currently use dynamic field names in projection like this using regex or another operator.

I am unsure if there will ever be the ability to, I am unable to find anything meaningful on the JIRA.

At the moment the best way is to restructure for your queries.

Upvotes: 1

Related Questions