Sort in CosmosDB Mongo APIs mandates indexing

Hello Experts,

I am in CosmosDB distribution of MongoDB. using 3.6X in JavaScript with MongoDB native client.

When I am using a sort:

  collection.find({}, {}). sort({field1: -1});

I always get this error as below?

"message": "Failed to retrieve the document:MongoError: Error=2, Details='Response status code does not indicate success: BadRequest (400); Substatus: 0; ActivityId: d05b7772-3252-4005-898f-4480cadfb8e1; Reason: (Response status code does not indicate success: BadRequest (400); Substatus: 0; ActivityId: d05b7772-3252-4005-898f-4480cadfb8e1; Reason: (Response status code does not indicate success: BadRequest (400); Substatus: 0; ActivityId: d05b7772-3252-4005-898f-4480cadfb8e1; Reason: (Message: {\"Errors\":[\"The index path corresponding to the specified order-by item is excluded.\"]}\r\nActivityId: d05b7772-3252-4005-898f-4480cadfb8e1, Request URI: /apps/e118124c-80f3-408e-a2f9-fbea51664ad4/services/5cb63213-f046-49d6-9825-0bfa4010772e/partitions/68271031-2d85-44cd-9929-8857ff69b63e/replicas/132696733163313635s/, RequestStats: Microsoft.Azure.Cosmos.Tracing.TraceData.ClientSideRequestStatisticsTraceDatum, SDK: Windows/10.0.17763 cosmos-netstandard-sdk/3.18.0);););"

So it needs an non-text indexing. Once it is indexed, it starts working fine.

Does it a MongoDB native behavior that sort only works with indexes? Or it’s something cosmosDB specific?

Thanks,
Pradip

Hi @Pradip_Speaks,

As I noted in your other topic, Cosmos’ API is a partial emulation of MongoDB with an entirely different server implementation. Unfortunately that means you cannot reference MongoDB server behaviour to understand how Cosmos’ implementation behaves. Your best resources are probably going to be the Cosmos DB API documentation and Azure Community Support.

This error message is specific to Cosmos: Troubleshoot common issues in Azure Cosmos DB’s API for MongoDB. It looks like Cosmos always requires a supporting index for queries.

MongoDB does not strictly require an index to sort results, but for best performance you should Use Indexes to Sort Query Results.

Regards,
Stennie

1 Like

Thanks. This is useful information @Stennie_X .

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.