2014-10-09 83 views
0

我有这样的文件结构蒙戈DB查询 - 利用最新一个分组结果

{ 
    lang: en, 
    origin: 'Origin Value', 
    key: 'Key', 
    translation: 'Translated value', 
    createdAt: <date> 
} 

因此,有各种不同的语言(恩,德,它等),也有很多关键的重复使用不同的日期(createdAt字段)。我需要构建一个查询,它将为每种语言的每个关键点采用最新的本地化,并按lang进行分组。

预期结果:

{ 
    en: [ 
    { 
     origin: 'Origin Value', 
     key: 'Key', 
     translation: 'Translated value', 
     createdAt: <the latest one date for this particular key>  
    }, 
    { 
     origin: 'Second Origin Value', 
     key: 'Second Key', 
     translation: 'Second Translated value', 
     createdAt: <the latest one date for this particular key>  
    } 
    ... 
    ], 
    de: [...], 
    it: [...], 
    ... 
} 

回答

1

在蒙戈外壳V2.6.4运行

var cursor = db.c.aggregate([ { 
    $sort : { 
     // sort to make sure the latest document of every group (lang, key) is at 
     // first location. 
     createAt : -1 
    } 
}, { 
    $group : { 
     _id : { 
      lang : "$lang", 
      key : "$key" 
     }, 
     doc : { 
      $first : "$$ROOT" // current entire document 
     } 
    } 
}, { 
    $group : { 
     _id : "$_id.lang", // regroup to combine all keys into one lang 
     body : { 
      $push : { 
       orgin : "$doc.origin", 
       key : "$doc.key", 
       translation : "$doc.translation", 
       createAt : "$doc.createAt" 
      } 
     } 
    } 
} ]); 

var result = {}; // store final result 
cursor.forEach(function(doc) { 
    result[doc._id] = doc.body; // aggregation pipeline can not process on key, 
           // this is a way to convert data to your 
           // expected format 
}); 

如果运行V2.6之前蒙戈外壳,在最后声明认为这种方式:

cursor.result.forEach(function(doc) { 
    result[doc._id] = doc.body; 
}); 
1

这应该为你做的工作,不知怎么的,所以首先在创建的结果进行排序和检索的第一个结果为使用$第一运营商各组:

db.dictionary.aggregate(
{$sort: {createdAt:-1}}, 
{$group: {_id:{lang: "$lang", key:"$key"}, createdAt:{$first:"$createdAt"}, origin: {$first:"$origin"}, translation: {$first:"$translation"}}}) 

顺便说一句,据我所知,你不能有聚合框架中的动态字段名称,所以你不能有语言键作为输出中的字段名称。

+0

我认为这是不正确使用'{ $ group:{_id:“$ key”,lang:{$ first:“$ lang”},createdAt:{$ first:“$ createdAt”},origin:{$ first:“$ origin”},translation:{ $第一: “$翻译”}}}'。因为在这个处理之后,每个**键**只会有一个** lang **,但实际上它可能会有几个** lang **。 – Wizard 2014-10-10 01:46:27

+0

你是对的;组ID需要是关键和郎,如在第二个查询 – cubbuk 2014-10-10 05:10:38

+0

谢谢你们,我还没有完全解决我的问题,但有足够的信息进一步调查。如果我有这样的话,会附上最终结果:) – 2014-10-11 11:31:36