Update Subdocument in Mongodb that stores id(s)

谁都会走 提交于 2019-12-11 06:46:22

问题


I am developing an application and we have decided to implement database with Mongodb, so I'm truly new to it. In database there is a collection for each company and we need to stores the ID(s) of each category of products of the company in a subdocument of company collection, Let's say we need to insert the following Object into collection:

{ 
  name : "comapnyX"
  address : {
     "street" : "main street",
     "ZipCode" : "12345" 
  },
  categories : [
     { "name" : "category1" },  
     { name" : "category2" } 
  ] 
}   

An then if later on we decide to update the categories, we need add one more category to this subdocument, how do I have to create that update?

please also let me know if this is not a good practice from Datamodeling point of view in Mongodb


回答1:


You can use the update method with the $push operator to add a new category:

db.collection.update( <query>,
                      { $push: { categories: {name: "category3" } }
                   )

MongoDB Docs on $push: http://docs.mongodb.org/manual/reference/operator/update/push/



来源:https://stackoverflow.com/questions/21502654/update-subdocument-in-mongodb-that-stores-ids

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