Mongodb 更新了很多 [英] Mongodb Update Many

查看:41
本文介绍了Mongodb 更新了很多的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 express js 和 npm 模块 mongodb 进行开发,并将 mongodb 作为数据库.我有两个集合,即用户"和活动".一个用户可以有 1000 个活动.

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. 首先,我将用户的 id、姓名和图片 url 存储到关系的活动文件.请告诉我这是否是错误的关系并建议用于存储关系的内容.

  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.

其次,我现在面临的问题是当我更新用户名时它不会在用户的活动中更新(这是
明显).我想要一些示例,以便我可以一次更新许多文档使用用户 ID.

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. 这是典型的一对多关系.因此,对于用户,您可以使用以下架构:

//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. 如果您想更新许多活动文档:

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

              

这篇关于Mongodb 更新了很多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆