Uploaded image for project: 'Core Server'
  1. Core Server
  2. SERVER-7313

Add Nested Data (Associative Array) and Index Support

      Within a document structure, I find that a lot of times it is more intuitive and easier to handle/manipulate nested data stored as associative arrays than regular arrays. With associative arrays, I get to avoid (imho) the awkward positional operator and its sometimes slicing and manipulation limitations. Unfortunately for us, the support for querying/indexing against associative arrays is very limited which forces the designer to resort back to regular arrays or create an alternate (synced) structure for querying purposes only.

      For demonstration purposes, let's say we have a collection that tracks all classes and their students. One document for each class and a student can belong to many classes.

      If we use a regular array to store the student info, then we have...

      db.class.save({_id: "class1", teacher:"Chris", students: [
      {_id: "asmith", grade: 97, rank: 1, stars:_id:"reading",count:5}, {_id:"math",count:8 },
      {_id: "bsmith", grade: 90, rank: 2, stars:_id:"reading",count:9}, {_id:"math",count:3 }
      ]
      });

      If we use an associative array to store the student info, then we have...

      db.classA.save({_id: "class1", teacher:"Chris", students: {
      "asmith" : {grade: 97, rank: 1, stars:{"reading":

      {count:5}

      , "math":{count:8}} },
      "bsmith" : {grade: 90, rank: 2, stars:{"reading":

      {count:9}

      , "math":{count:3}} }
      }
      });

      The following are some basic tasks that we would like to perform (against both collections). Criteria for performing the tasks is that they must be done in one command (atomic purposes) and any query must involve indexes only.

      -Pull only asmith's student info (not all students) from each of his classes:

      Regular: Not sure if that is possible?
      Associative: db.classA.find({"students.asmith":{$exists:true}},

      {"students.asmith"}

      ); //see below about this weak index

      -Pull only asmith's student info along with the teacher's name of the class in one query:

      Regular: Not possible?
      Associative: db.classA.find({"students.asmith":{$exists:true}},

      {"students.asmith","teacher"}

      );

      -Update asmith's grade in class1:

      Regular: db.class.update({_id:"class1", "students._id":"asmith"}, {$set:{"students.$.grade":96}});
      Associative: db.classA.update({_id:"class1"}, {$set:{"students.asmith.grade":96}});

      -Increment asmith reading star count (nested nested structure):

      Regular: Not possible (yet) - see https://jira.mongodb.org/browse/SERVER-831
      Associative: db.classA.update({_id:"class1"}, {$inc:{"students.asmith.stars.reading.count":1}});

      As the above examples demonstrate, it would be more straightforward to use an associative array.
      However the indexing/querying support is limited so we cannot perform the following very basic task:

      -Search for students with a grade 90 or higher.

      Unlike the regular array structure, there is no way to search against grades using an index. I find this lack of support to be surprising given that arrays and associative arrays really only differ in keys; one is implicitly implied (sequential integer) while the other is explicitly set by the user. In theory, positional operator could work with both types of keys.

      Suggestion: Add index support at nested array level (regardless if is regular or associative):

      db.classA.ensureIndex(

      {"students.*.grade"}

      ); //character indicates associative array; this could technically work with regular arrays as well
      db.classA.find({"students.*.grade":{$gte:90}}); //not only is query field name intuitive but it matches the same naming convention used in the index declaration
      db.classA.update({"students.*.grade":{$gte:90}}, {$inc:{"students.$.grade":1}}); //positional operator example

      Consequences (Wins):

      -We are not forced thinking one way when structuring nested data or in some cases creating synced alternate data store to achieve our goals.

      The user should have the freedom to organize data and associate keys with it at the same time. In essence the data becomes true "sub-documents" where each data has its own unique identifier just like the main document record (_id).

      I cannot tell how many times I have come across users on the internet unaware of the index limitation and forced to restructure their data.

      -good "$exists" index performance against associative array keys is possible

      In the MongoDB documentation (Advanced Queries section), it states that "$exists is not very efficient even with an index".
      If indexes within associative arrays were supported, then the workaround to ensure good index performance to see if a user exists in a class is to store the username (key) inside the associative array values and index that field.

      E.g.
      students: {
      "asmith" : {_id: "asmith", grade: 97, rank: 1, ...},
      "bsmith" : {_id: "bsmith", grade: 90, rank: 2, ...}
      }

      db.classA.ensureIndex("students.*._id");
      db.classA.query(

      {"students.*._id":"asmith"}

      ); //instead of using {"students.asmith":{$exists:true}}

      Or better yet, maybe MongoDB can implicitly do that behind the scenes using some internal field when we index against the associative array.

      Other Readings:

      http://developer.bazaarvoice.com/mongodb-arrays-and-atomicity - Nice article on the benefits of using associative arrays (solved atomicity issues)

            Assignee:
            Unassigned Unassigned
            Reporter:
            a_niceguy57 Steve K
            Votes:
            6 Vote for this issue
            Watchers:
            8 Start watching this issue

              Created:
              Updated:
              Resolved: