2016-07-14 78 views
0

我需要使用在另一個集合中選取的值更新集合的字段。我使用需要更新的字段的值來查找其他集合中的新值。MongoDB更新值與在另一個集合上執行查詢的結果

我試試這個:

db.Organizations.find({}).forEach(function(doc) { 
    print(doc.Country.DisplayName); 
    var c = db.Countries.find({"DisplayName": doc.Country.DisplayName}); 
    doc.Country = c; 
    print(doc.Country.DisplayName); 
}); 

結果:

Philippines 
[unknown type] 

我怎樣才能做到這一點? 在此先感謝。

編輯: 我發現使用findOne()解決方案(還有我的集合中沒有重複的國家)

var index = 0; 
db.Organizations.find({"Country": { $ne: null }}).forEach(function(doc) { 
    print(index + ': ' + doc.Country.DisplayName); 

    var myDoc = db.Countries.findOne({"DisplayName": doc.Country.DisplayName}); 
    if (myDoc){ 
     print(index + ': ' + myDoc); 
     doc.Country = myDoc; 
     print(index + ': ' + doc.Country.DisplayName); 
    } 

    index++; 

}); 

而結果:

0: Philippines 0: [object BSON] 0: Philippines 1: Singapore 1: [object BSON] 1: Singapore

+0

你想做什麼? **更新**一個集合中的文檔?請向我們展示兩個收藏的示例文檔以及預期結果。 – styvane

+0

我想更新組織集合的字段「國家」,並在國家/地區收藏中執行查詢。結果必須是'菲律賓菲律賓' – Karine

+0

我們可以看到你的文件嗎? – styvane

回答

1

第二find(...)也是異步所以你必須通過這樣的回調,就像這樣:

db.Organizations.find({}).forEach(function(doc) { 
    print(doc.Country.DisplayName); 
    db.Countries.find({"DisplayName": doc.Country.DisplayName}, function(err, cursor) { 
     doc.Country = cursor.next(); 
     print(doc.Country.DisplayName);   
    }); 
}); 
+0

它似乎沒有工作,我可以打印注意吧'菲律賓 新加坡 香港 香港 新加坡 香港 香港 香港 香港 香港 香港 新加坡 新加坡 新加坡 巴基斯坦 新加坡 新加坡 香港'但我找到了一個解決方案,使用'findOne()' – Karine

相關問題