Update Subdocument in Mongodb that stores id(s)

2019-08-04 00:50发布

问题:

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/



标签: mongodb nosql