Google Groups

Re: indexing queries involving dates and boolean flags


Bernie Hackett Sep 20, 2011 5:02 PM
Posted in group: mongodb-user
It will work:

> db.foo.insert({'my_flag_field': true, 'my_date_field': new Date()})
> db.foo.find()
{ "_id" : ObjectId("4e791e6a45c4bf56905ed349"), "my_flag_field" :
true, "my_date_field" : ISODate("2011-09-20T23:14:50.592Z") }

> db.foo.ensureIndex({'my_date_field': 1, 'my_flag_field': 1})

> db.foo.find({my_flag_field:true}).sort({my_date_field:1}).explain()["cursor"]
BtreeCursor my_date_field_1_my_flag_field_1

> db.foo.find().sort({my_date_field: 1}).explain()["cursor"]
BtreeCursor my_date_field_1_my_flag_field_1


On Sep 20, 4:51 pm, Sergei Tulentsev <sergei.tulent...@gmail.com>
wrote:
> To use compound index, you have to query only on fields that are listed
> first in the index definition.
> So, this one won't support second query.
>
>
>
>
>
>
>
>
>
> On Wed, Sep 21, 2011 at 3:17 AM, Bernie Hackett <ber...@10gen.com> wrote:
> > One idea would be to create a compound key index on {my_date_field: 1,
> > my_flag_field: 1}. That index will be used for both queries.
>
> >http://www.mongodb.org/display/DOCS/Indexes#Indexes-CompoundKeysIndexes
>
> > On Sep 20, 9:38 am, Jeff Lee <jeffoma...@gmail.com> wrote:
> > > Apologies, I've got a very noob-seeming question here.
>
> > > I've got a collection that has boolean flag and a date field. In all
> > > cases I want to sort by the date field, and sometime I care about the
> > > value of the boolean flag, and sometimes I don't.
>
> > > In other words, sometime I will do this:
>
> > >     db.collection.find().sort({my_date_field:1})
>
> > > And sometimes I will do this:
>
> > >     db.collection.find({my_flag_field:false}).sort({my_date_field:1})
>
> > > In this case, is it dramatically preferable to use a multi-key index,
> > > involving both the flag and date fields, rather than a single-key
> > > index on the date field? How can I conceive of the differences between
> > > these two, under the hood?
>
> > --
> > You received this message because you are subscribed to the Google Groups
> > "mongodb-user" group.
> > To post to this group, send email to mongod...@googlegroups.com.
> > To unsubscribe from this group, send email to
> > mongodb-user...@googlegroups.com.
> > For more options, visit this group at
> >http://groups.google.com/group/mongodb-user?hl=en.
>
> --
> Best regards,
> Sergei Tulentsev