Request another collection inside forEach

I want to do something like:

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}}) }) 

The problem is that db.items.find({_id: doc.item_id}) returns something that I cannot directly access the document properties. What would be the right way to do this? Thanks!

db.items:

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

The find() function returns a cursor , you need to iterate:

When the find () method returns documents, the method actually returns the cursor to the documents

Your code has been updated:

 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}}); }) }) 

or you can use findOne() , which returns one of the relevant documents.

 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}}) }) 
+13
source

Source: https://habr.com/ru/post/979005/


All Articles