Return sorted array elements in some field

Hello,
I see from this documentation page https://www.mongodb.com/docs/manual/core/indexes/index-types/index-multikey/create-multikey-index-basic/#std-label-index-create-multikey-basic
the following sentence:

The index contains a key for each individual value that appears in the test_scores field. The index is ascending, meaning the keys are stored in this order: [ 62, 73, 88, 89, 92, 97 ] .

However I do not see how to write a find query that would return me these values (1 per row) in that order along _id of each object (also sorted by _id if there are dupes). Of course all this efficiently using the index and specifying a limit, and allowing to paginate the results in N chunks.

ie something like:
{“test_scores”: 62, “_id”: SomeObjId}
{“test_scores”: 73, “_id”: SomeObjId}
etc…

I hope it makes sense,
Thanks in advance
Best

1 Like

I answered this question via email. In short, you can do an $unwind on test_scores.

Hi Ger,

Thanks for replying, I was just wondering why it would not be possible to get same output using just “regular” find() with possibly some option or whatever. That’s what Couchbase provides when using UNNEST clause. I see MongoDB welcomes community contributions and I’d be more than happy to contribute if that’s possible.

As aside question, I was also wondering if MongoDB server could provide low level index API access that would allow a client to read some index key ranges ? For example somehow get directly the [ 62, 73, 88, 89, 92, 97 ] values from scores example.

Thanks
Best regards

You should be able to use distinct to get all of the test_scores.