JayC
JayC

Reputation: 2292

How to add new values into existing data in MongoDb?

Currently I have a value such as; ID, name, age. In my database it is filled over with 100 queries of these.

db.students.insert(
    { id: 001, name : "Eva", age: 21 })

How can I update this where I can add new values such as; Id, name, age, height, weight.

Attempt

db.students.update(
    { id: 001, name : "Eva", age: 21, height: 5, weight: 100 })

Is it possible to add height and weight to existing data without deleting the values and reenter it?

Upvotes: 1

Views: 3723

Answers (1)

satish chennupati
satish chennupati

Reputation: 2650

You need to use $set with update. an example would be

db.products.update(
   { _id: 100 },
   { $set:
      {
        quantity: 500,
        details: { model: "14Q3", make: "xyz" },
        tags: [ "coats", "outerwear", "clothing" ]
      }
   }
)

behavior of $set

If the field does not exist, $set will add a new field with the specified value, provided that the new field does not violate a type constraint. If you specify a dotted path for a non-existent field, $set will create the embedded documents as needed to fulfill the dotted path to the field.

If you specify multiple field-value pairs, $set will update or create each field.

Upvotes: 1

Related Questions