2016-07-14 77 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

相关问题