[英]Merge and aggregate some fields of two or more collections with identical schema mongodb
我有一些具有相同架構的集合,我想對它們執行合並+聚合。 模式很簡單,如下所示:
{ 'fr': 1, 'to': 1, 'wg': 213}
{ 'fr': 1, 'to': 2, 'wg': 53}
{ 'fr': 2, 'to': 2, 'wg': 5521}
以下代碼可用於合並兩個集合,但是我想知道是否有更快的解決方案和/或一個解決方案可以以類似的方式合並多個集合而無需創建嵌套調用:
var c = db.collection('first').find()
c.each(function(err, doc) {
if (err) throw err
if (doc == null) {
console.log('done')
return
}
db.collection('second').findOne({
'fr': doc['fr'],
'to': doc['to']
}, function(err, doc2) {
if (err) throw err
db.collection('my_results').save({
'fr': doc['fr'],
'to': doc['to'],
'wg': doc['wg'] + doc2['wg']
}, function(err) {
if (err) throw err
})
})
})
這里沒有絕對的免費操作,因為您無法使用MongoDB進行聯接。 但是您可以使用mapReduce及其某些功能來獲得所需的輸出。
因此,首先創建一個映射器:
var mapper = function () {
emit( { fr: this.fr, to: this.to }, this.wg )
};
然后是減速器:
var reducer = function (key,values) {
return Array.sum( values );
};
然后,運行mapReduce操作,將輸出設置為另一個集合:
db.first.mapReduce(mapper,reducer,{ "out": { "reduce": "third" } })
注意此處的“ out”選項,本手冊部分對此進行了說明 。 關鍵是,盡管控制台中可能會誤導統計信息輸出,但“ reduce”語句非常重要。 這樣,當我們針對另一個集合運行相同的代碼時:
db.second.mapReduce(mapper,reducer,{ "out": { "reduce": "third" } })
結果實際上發生的是,第一個操作的輸出也傳遞到第二個操作的“減少”階段。
最終結果是兩個集合中所有具有相同鍵值的值都將被添加到“第三個”集合中:
{ "_id" : { "fr" : 1, "to" : 1 }, "value" : 426 }
{ "_id" : { "fr" : 1, "to" : 2 }, "value" : 106 }
{ "_id" : { "fr" : 2, "to" : 2 }, "value" : 11042 }
你可以讓一個小票友如果你想你的fr
和to
是兩個候選條件的任意順序的獨特組合,甚至跑過來這些結果另一個MapReduce的或聚合。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.