Proper Index order when using positional operator

14 views
Skip to first unread message

ajm244

unread,
Apr 23, 2014, 4:06:50 PM4/23/14
to mongod...@googlegroups.com
I have a collection structured like this:

tag_analytics:
{
    tag_id
: "test1",
    zips
: [ {zip_code: "90210", value: 2}, {zip_code: "90310", value: 4} ],
    report_time
:ISODate("2014-03-23T00:00:00"),
    value1
: 1,
    value2
: 2
}


I am curious how I would make an index for the following update call:

db.tag_analytics.update({report_time:ISODate("2014-04-23T00:00:00"), tag_id: "test1", "zips.zip_code":"90210"},{$inc:{zips.$.value":10}});



If I needed to guess it would be
db.tag_analytics.ensureIndex({report_time:-1, tag_id:1, "zips.zip_code":1});

but I am unsure if my zips.zip_code should be first or last, or if it is possible to index this query at all.  Any help would be greatly appreciated.

Thank you,

Andrew Ryder

unread,
May 26, 2014, 11:51:55 PM5/26/14
to mongod...@googlegroups.com
Hello!

Yes, that index will work and likely be used for your given update command. The order of the fields in the index doesn't matter for the only query you've given (the match portion of the update), however, there are considerations that you may wish to take into account to make your index work in other situations. For example, will you always know the exact date? The earlier in an index a field occurs, the more precise you need to be with the queries to make good use of it - the only example you have provided specifies all 3 fields precisely, if that is your only use case then you're in a really strong position. Sorting results of a query is another consideration. You can read more about compound index considerations in the documentation.

I hope this helps.

Kind regards,
Andrew

Reply all
Reply to author
Forward
0 new messages