MongoDB copy a field to another collection with a foreign key

后端 未结 2 1221
花落未央
花落未央 2021-01-18 03:37

I want to copy over the color from user collection to the Car collection. I\'m using a foreign key which is userID.

> db.test1.User.find()
{ \"_id\" : Obj         


        
2条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-18 04:12

    Here are my two cents: you can drop "function(x)". I prefer the following syntax:

    db.source_collection_name.find().forEach(
      doc=>
          db.target_collection_name.update(
            {"_id": doc._id},
            {$set: {"field_to_update": doc.field}}
          )
    )
    

    In your case, something like this should work:

    db.test1.User.find().forEach(
      doc=> 
        db.test2.Car.update( 
          { "userID": doc._id }, 
          { $set: { "color": doc.Color} } 
        ) 
    );
    

提交回复
热议问题