Update Subdocument in Mongodb that stores id(s)

2019-08-04 00:41发布

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

标签: mongodb nosql
1条回答
对你真心纯属浪费
2楼-- · 2019-08-04 00:42

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/

查看更多
登录 后发表回答