Mongodb Update Many

后端 未结 2 501
盖世英雄少女心
盖世英雄少女心 2021-01-29 05:47

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

相关标签:
2条回答
  • 2021-01-29 06:29
    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
      });
    
                  

    0 讨论(0)
  • 2021-01-29 06:29

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

    0 讨论(0)
提交回复
热议问题