0

i'm new to mongodb is there any option to append new data set into collection. i.e in 'student',

{name: 'Tom', age: 28, marks: [{subject: "English", marks: 90},{subject: "Maths", marks: 100},{subject: "Computes", marks: 20}]}

in this 'student' collection how to insert new subject and marks like

{subject:"chemistry", marks:30}

I know it may be silly question but pls help me on this Thanks

  • Does this answer your question? [How to insert an element to MongoDB internal list?](https://stackoverflow.com/questions/13987365/how-to-insert-an-element-to-mongodb-internal-list) – MauriRamone Jan 08 '20 at 13:20
  • yep thanks but @Wernfried Domscheit also made me impressed with his answer – Mr.Tiffenbox Jan 08 '20 at 13:28

2 Answers2

2

Try this one:

db.students.updateOne(
   { name: 'Tom' },
   {
      $push:
         { marks: { subject: "chemistry", marks: 30 } }
   },
);

Note, $push will add the element every time you execute the command. If you want to add the element only once then use:

db.students.updateOne(
   { name: 'Tom' },
   {
      $addToSet:
         { marks: { subject: "chemistry", marks: 35 } }
   }
);

This will append element { subject: "chemistry", marks: 30 } only once. Note, if you run { subject: "chemistry", marks: 31 } then it will be added also.

In case you like to insert chemistry just once then you can use this:

db.students.updateOne(
   {
      name: 'Tom',
      "marks.subject": { $nin: ["chemistry"] }
   },
   {
      $push:
         { marks: { subject: "chemistry", marks: 30 } }
   }
);
Wernfried Domscheit
  • 54,457
  • 9
  • 76
  • 110
1

Using Update and $push as follows

db.collection.update(
    { name: 'Tom'}, 
    {$push: {'marks': {subject:"chemistry", marks:30}}}
)
MauriRamone
  • 469
  • 1
  • 3
  • 21