3

a quick question regarding how to define a compound index

as per the definition I can create a compound index as below and it would create a compound index for student_id and class_id.

db.students.createIndex({"student_id":1,"class_id":1});

however what will happen if I give something like this

db.students.createIndex({"student_id,class_id":1})

the syntax is valid and it accepts the index, but I am not sure how the index would be created.

any thoughts ?

DAXaholic
  • 33,312
  • 6
  • 76
  • 74
user641887
  • 1,506
  • 3
  • 32
  • 50

1 Answers1

1

Well if you do that and then just run db.students.getIndexes() you will see that the index is created for a field called student_id,class_id - which is exactly what you asked for, i.e. not a compound index but an index on a field with a comma in its name.

{
    "v" : 1,
    "key" : {
        "student_id,class_id" : 1.0
    },
    "name" : "student_id,class_id_1",
    "ns" : "tmp.students"
}
DAXaholic
  • 33,312
  • 6
  • 76
  • 74
  • shouldnt mongodb throw an exception there since there does not exists a field by that name? – user641887 Aug 16 '16 at 04:46
  • mongoDB is not a SQL database with strict schemas. There are even features which are directly targeting the fact that there may be documents without the indexed field and therefore don't create index entries for them - see https://docs.mongodb.com/manual/core/index-sparse/ – DAXaholic Aug 16 '16 at 04:47