Reputation: 10922
I have 100000 documents and I need to retrieve the top 10 documents that have the highest values.
Here's an example of a simplified document:
{
"_id" : ObjectId( "4f2fbeb0369a2ba603000000" ),
"usage" : {
"2012" : {
"2" : {
"project" : {
"4f182a76369a2b2903000000" : {
"site" : {
"1" : 5,
"2" : 1
}
}
}
}
}
}
}
The value that the sort/limit will be applied to can be found in 'usage.2012.2.project.4f182a76369a2b2903000000.site.1' (in the case of the above example, the value is 5).
The problem is that in some documents this object exists, in others it won't.
Now I could use $exists to check if the object exists, but according to the MongoDB manual using $exists is inefficient. Are there any alternative ways that I could go about doing this? I can change the schema if required to suit..
Upvotes: 2
Views: 1713
Reputation: 5041
If you query based on a value that does not exist in certain documents, the documents that do not contain the value are excluded from the result set. You should not have to filter them using $exists in advance.
db.collection.find().sort( { "usage.2012.2.project.4f182a76369a2b2903000000.site.1" : -1 } ).limit(10)
The query above will only return up to 10 values - it will not regard documents where the sorting field doesn't exist.
Upvotes: 3