Ad

How To Add Data To An Already Existing Item In Mongodb

So i have a collection called 'users'. Where it lists a list of users and profile info.They are all stored inside mongodb. I want to add the option where they can add more pictures to their profile.For example I just want to add an extra "4":"newpicture.png" to "Documents" in the item inside the collection. How do I add a subsection to this item without having to rewrite all the data?

Eample of current data

{
  "name": "Oran",
  "username": "Oran.Hammes",
  "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/brandonflatsoda/128.jpg",
  "email": "[email protected]",
  "dob": "1953-03-21T17:40:17.020Z",
  "phone": "364-846-1607",
  "address": {
    "street": "Schultz Stream",
    "suite": "Suite 618",
    "city": "North Muriel mouth",
    "zipcode": "06447-1081",
    "geo": {
      "lat": "57.1844",
      "lng": "-56.8890"
    }
  },
  "website": "misty.net",
  "company": {
    "name": "Hettinger, Reilly and Stracke",
    "catchPhrase": "Multi-tiered system-worthy database",
    "bs": "best-of-breed evolve e-markets"
  },
  "Documents":{
    "1":"image.png",
    "2":"Test.jpg",
    "3":"Next.png"
  }
}

with .update({ username: "Oran.Hammes" },{$set: {"Documents" :{"4": "newpicture.png"}}})

enter image description here

Ad

Answer

Mongo has the $set part of its update command for updating values within a single document. You can read more about modifying documents here: https://docs.mongodb.org/manual/tutorial/modify-documents/

An example would be:

db.users.update(
    { "username": "Oran.Hammes" },
    {
        $set: {
            "Documents.4" : "newpicture.png"
        }
    }
)

With regards to whether or not you will need to rewrite the data, refer to this question: Does MongoDB $set write just the field or the whole document? . Basically, this depends on how you setup your database, and how much memory is allocated to each document.

Ad
source: stackoverflow.com
Ad