Hi there,
Say I have an array of items in a collection, and I index two properties in the items, I can do queries on the properties and it will use the correct compound index bounds:
db.test.insertMany([
{ items: [{ a: 2, b: 2 }] },
{ items: [{ a: 1, b: 7 }] },
{ items: [{ a: 2, b: 5 }] },
{ items: [{ a: 1, b: 2 }] },
]);
db.test.createIndex({ 'items.a': 1, 'items.b': 1 });
db.test.find({
items: {
$elemMatch: {
a: { $gt: 0 },
b: { $gt: 0 }
}
}
});
The documents will also be returned in ascending order of the indexes:
[
{
_id: ObjectId("642658957af10b1de797d5ef"),
items: [ { a: 1, b: 2 } ]
},
{
_id: ObjectId("642658957af10b1de797d5ed"),
items: [ { a: 1, b: 7 } ]
},
{
_id: ObjectId("642658957af10b1de797d5ec"),
items: [ { a: 2, b: 2 } ]
},
{
_id: ObjectId("642658957af10b1de797d5ee"),
items: [ { a: 2, b: 5 } ]
}
]
When I specify a sort, it will always do an in-memory sort though. Is there a way to sort the results with use of the index? Or, if not, is there a way to return the results in naturally reversed order for the index?
I have tried some of the following:
.sort({ 'items.a': 1 })
.sort({ 'items.b': 1 })
.sort({ 'items.a': 1, 'items.b': 1 })
If this is not possible, I know I can just split the items array off into a separate collection and index on it, but I just would like to know if this sort of sorting is possible before I do this.
Many thanks!