2014-12-02 68 views
6

其他集合我想做的事情是這樣的:查詢裏面的forEach

db.ratings.find().forEach(function(doc){ 

    var item = db.items.find({_id: doc.item_id}) 
    var ry = item.detail.ry 
    db.ratings.update(doc,{$set: {itd: ry}}) 

}) 

的問題是,db.items.find({_id: doc.item_id})正在恢復的東西,我不能直接調用文檔屬性。這是否是正確的做法?謝謝!

db.items:

{ 
    "_id" : ObjectId("5461c8f0426f727f16000000"), 
    "n" : "The Shawshank Redemption", 
    "detail" : { 
     "ry": 1992 
    } 
} 
+1

use db.items.findOne({_ id:doc.item_id}); – Disposer 2014-12-02 19:40:48

回答

13

find()函數返回一個cursor,你需要遍歷它:

當find()方法「返回的文檔」的方法實際上是 將光標返回到文檔

您的代碼,已更新:

db.ratings.find().forEach(function(doc){ 

    db.items.find({_id: doc.item_id}).forEach(function(item){ 
    var ry = item.detail.ry; 
    db.ratings.update(doc,{$set: {itd: ry}}); 
    }) 
}) 

或者您可以使用findOne(),它返回其中一個匹配文檔。

db.ratings.find().forEach(function(doc){ 

    var item = db.items.findOne({_id: doc.item_id}) 
    var ry = item.detail.ry 
    db.ratings.update(doc,{$set: {itd: ry}}) 

}) 
+1

天才!謝謝 – 2015-10-26 17:21:46

+0

@BatScream如何處理重複錯誤? – 6339 2017-07-12 12:05:05