I have a document with embedded documents in an array. The prupose is to allow alias logins, that is: one user needs to be able to have several logins (username+company_id+pwd) since he or she may belong to different companies.
It looks somethine like this:
{
name : "James D"
logins : [
{company_id : 1, username : "james", pwd : "****"},
{company_id : 2, username : "james.d", pwd : "****"},
{company_id : 3, username : "jd", pwd : "****"}
]
}
I want to index to company_id and username, which I did using
> db.user.ensureIndex({"logins.username" : "james", "logins.company_id" : 1})
And here’s my question, does the index work? Is the query acutally using the index? I’m asking because (1) I am not sure if MongoDB handles this kind of indexes, and (2) I’m not sure how to interpret the explain() function.
> db.user.find({"logins.username" : "james", "logins.company_id" : 1}).explain()
{
"cursor" : "BtreeCursor username.color_1_logins.company_id_1",
"nscanned" : 3,
"nscannedObjects" : 3,
"n" : 2,
"millis" : 1,
"nYields" : 0,
"nChunkSkips" : 0,
"isMultiKey" : true,
"indexOnly" : false,
"indexBounds" : {
"logins.username" : [
[
"blue",
"blue"
]
],
"logins.company_id" : [
[
{
"$minElement" : 1
},
{
"$maxElement" : 1
}
]
]
}
}
Those indexes are allowed and yours seems to be working. Every array element is added to the index seperately so indexing on large arrays might quickly increase the size of your index. For a few aliases of a username that should not be an issue though.