Mongodb Update Many

笑着哭i 提交于 2021-02-05 12:24:54

问题


I am developing using express js and npm module mongodb with mongodb as database. I have two collections namely "users" and "activities". There can be 1000s of activities of a User.

  1. Firstly I am storing id, name and picture url of the user into the activity document for relation. Please tell me if this is wrong for relations and suggest something for storing the relation.

  2. Secondly the problem I am facing now is when I update a user's name it doesn't get updated in the activities of the user (which is
    obvious). I want some example so that I can update many docs at once using the user id.

Please help on the above. Thanks in advance.


回答1:


  1. This is typical one-to-many relationship. So in case of the User you can have the following schema:

//User
{
  //_id: ObjectId - this one is unique and inserted to every document by default  
  profile: String,
    ...
}
  
//Activity
{
  description: String,
  ...,

  userId: String, // referecing the user _id, e.g. "56a5eccb2258799919dc2c40"
}
  
  1. If you want to update many docs for activity:

db.activities.update({ userId: '56a5eccb2258799919dc2c40' }, { 
    $set: {
      description: 'new description'
    } 
  },
  {
    multi: true //means update all matching docs
  });

              



回答2:


You should store just the _id of the User in the Activity. Then use that to access the User via the Activity (if that's what you want to do).



来源:https://stackoverflow.com/questions/35037566/mongodb-update-many

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!