在嵌入式文档上使用MongoDB Group

时间:2012-07-10 17:27:18

标签: mongodb

我的用于的文档如下所示:

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

为此,以下组命令有效,以便从我的文档中获取不同的DisciplineNames和DisciplineCodes

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: { } 
});

但是,我的文档现在已更改为:

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

如您所见,Discipline是一个嵌入式文档。

如何修改我的群组命令仍然这样做?

1 个答案:

答案 0 :(得分:3)

我相信您正在尝试返回一份文档,其中列出了所有不同的学科代码和名称组合。在你的第一个组命令中,我认为不会调用reduce函数(如果我错了,请纠正我。)

为了获得嵌入代码和名称的所有不同的学科组合,您可以使用点表示法:

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

输入:

{ "_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 } }

结果:

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