[SERVER-13933] compound index with numeric keys only Created: 13/May/14  Updated: 10/Dec/14  Resolved: 02/Dec/14

Status: Closed
Project: Core Server
Component/s: Index Maintenance
Affects Version/s: 2.4.4, 2.6.1
Fix Version/s: None

Type: Question Priority: Minor - P4
Reporter: Ben Rotz Assignee: Unassigned
Resolution: Duplicate Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Issue Links:
Duplicate
duplicates MONGOSH-1037 Numeric field are sorted to the front... Closed
Participants:

 Description   

Is there a way to create a compound index in mongo with "numeric" keys? I imagine that mongo is sorting the object I pass it numerically after calling the ensureIndex function, which results in a compound key order of 1,2,3 instead of the desired 1,3,2.

Thank you for any help you can provide

> db.test.drop();
true
> db.test.ensureIndex({'1' : 1, '3' : 1, '2' : 1});
{
        "createdCollectionAutomatically" : true,
        "numIndexesBefore" : 1,
        "numIndexesAfter" : 2,
        "ok" : 1
}
> db.test.getIndexes();
[
        {
                "v" : 1,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_",
                "ns" : "test.test"
        },
        {
                "v" : 1,
                "key" : {
                        "1" : 1,
                        "2" : 1,
                        "3" : 1
                },
                "name" : "1_1_2_1_3_1",
                "ns" : "test.test"
        }
]



 Comments   
Comment by Thomas Rueckstiess [ 15/May/14 ]

Hi Ben,

The issue appears to be how the shell converts documents with numeric key names. A quick test shows that the shell re-orders the fields before sending it to the server:

> a = {"3":1, "2":1}
{ "2" : 1, "3" : 1 }

This is related to how arrays are stored as BSON. From the BSON spec page under "Notes":

Array - The document for an array is a normal BSON document with integer values for the keys, starting with 0 and continuing sequentially. For example, the array ['red', 'blue'] would be encoded as the document {'0': 'red', '1': 'blue'}. The keys must be in ascending numerical order.

I tested building an index on numeric keys from the Python driver, which uses a list to specify the key order, and that works without re-ordering the fields. I suspect other drivers will offer similar ways to preserve the order of index keys, so you should be able to create these indexes in correct order through a driver.

Regards,
Thomas

Generated at Thu Feb 08 03:33:20 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.