Index correctly to optimize a query

0

I have a problem with a query type for MongoDB. In a data collection I have indexed almost all fields with {a: 1}, {b: 1} ... and queries like the following have a very good performance:

db.installations.find({deviceToken:"mydevicetoken"})

The following query with the indexed fields, takes much more so I deduce that I have not used the indexing correctly:

db.installations.find({ created_at: { $lte : ISODate("2016-12-24T06:44:59.999Z"),
                    $gte : ISODate("2016-12-23T21:45:00Z") } } ).sort( { created_at: 1 })

This last query throws me a lot of time in the mongotop to the point that it collapses the database due to excessive consultation time. Someone would know how to solve it. Thanks

    
asked by Santi 04.04.2017 в 13:59
source

1 answer

0

How is your index currently? Since if you have a compound or multiple index, that can be the factor of the excess of time in the query. You can review it with:

db.installations.getIndexes()

You can delete it with:

db.installations.dropIndex('created_at')

You can create a simple index, with that it should be enough so that your query does not collapse the database:

db.installations.createIndex({created_at: 1})

I would do the query like this:

db.installations.find({created_at: {$gte: new Date('2016-12-23'), $lt: new Date('2016-12-24')}}).sort({created_at: 1}).pretty()

I leave you the index documentation of mongodb

    
answered by 05.04.2017 / 20:29
source