Alex
Alex

Reputation: 38519

Using MongoDB Group on embedded documents

My document used to look like this:

{
  _id : 47cc67093475061e3d95369d, 
  Name : "A name", 
  Description  : "Some description",
  DisciplineCode  : "105",
  DisciplineName  : "A Name",
  OtherProperty : "Something"
}

For which, the following group command worked, in order to get the distinct DisciplineNames and DisciplineCodes from my documents

disciplines = db.result.group({ 
    key: {DisciplineName:1, DisciplineCode:1}, 
    reduce: function(obj, prev) { if (!obj.hasOwnProperty("DisciplineName")) { 
        prev.DisciplineName = obj.DisciplineName; 
        prev.DisciplineCode = obj.DisciplineCode; 
    }}, 
    initial: { } 
});

However, my document has now changed to:

{
  _id : 47cc67093475061e3d95369d, 
  Name : "A name", 
  Description  : "Some description",
  Discipline: {
    Code  : "105",
    Name  : "A Name"},
  OtherProperty : "Something"
}

As you can see, Discipline is an embedded doc.

How can I modify my group command to still do the same?

Upvotes: 1

Views: 843

Answers (1)

Jenna
Jenna

Reputation: 2396

I believe that you are trying return a document that lists all distinct combinations of discipline code and name. In your first group command, I don't think the reduce function is called (please correct me if I'm wrong).

To get all distinct combinations of discipline now that code and name are embedded, you can use dot notation:

db.example.group({
    key: {"discipline.name": 1, "discipline.code":1},
    initial: {},
    reduce: function(obj, prev){}
})

input:

{ "_id" : 1, "doc" : { "name" : "Jenna", "number" : 1 } }
{ "_id" : 2, "doc" : { "name" : "Jenna", "number" : 2 } }
{ "_id" : 3, "doc" : { "name" : "Jenna", "number" : 2 } }
{ "_id" : 4, "doc" : { "name" : "J", "number" : 2 } }
{ "_id" : 5, "doc" : { "name" : "J", "number" : 1 } }

result:

[ 
        {
            "doc.name" : "Jenna",
            "doc.number" : 1
        },
        {
            "doc.name" : "Jenna",
            "doc.number" : 2
        },
        {
            "doc.name" : "J",
            "doc.number" : 2
        },
        {
            "doc.name" : "J",
            "doc.number" : 1
        }
    ]

Upvotes: 3

Related Questions