Collection events have a userId and an array of events - each element in the array is an embedded document. Example:
{ "_id" : ObjectId("4f8f48cf5f0d23945a4068ca"), "events" : [ { "eventType" : "profile-updated", "eventId" : "247266", "eventDate" : ISODate("1938-04-27T23:05:51.451Z"), }, { "eventType" : "login", "eventId" : "64531", "eventDate" : ISODate("1948-05-15T23:11:37.413Z"), } ], "userId" : "junit-19568842",
}
Using a query similar to the one below, you need to determine the events generated in the last 30 days:
db.events.find( { events : { $elemMatch: { "eventId" : 201, "eventDate" : {$gt : new Date(1231657163876) } } } } ).explain()
The query plan shows that the index in "events.eventDate" is used when the test data contains fewer events (about 20):
{ "cursor" : "BtreeCursor events.eventDate_1", "nscanned" : 0, "nscannedObjects" : 0, "n" : 0, "millis" : 0, "nYields" : 0, "nChunkSkips" : 0, "isMultiKey" : true, "indexOnly" : false, "indexBounds" : { "events.eventDate" : [ [ ISODate("2009-01-11T06:59:23.876Z"), ISODate("292278995-01--2147483647T07:12:56.808Z") ] ] }
}
However, when there are a large number of events (about 500), the index is not used:
{ "cursor" : "BasicCursor", "nscanned" : 4, "nscannedObjects" : 4, "n" : 0, "millis" : 0, "nYields" : 0, "nChunkSkips" : 0, "isMultiKey" : false, "indexOnly" : false, "indexBounds" : { }
}
Why is the index not used when there are many events? Maybe when there are a large number of events, MongoDB believes that it is effective to scan all elements except using the index?