Collection.upate()

i have a collection as bellow

{
classic : 1
section: 'A'
teachers[
{id :123,
name:"teacher 1",
isClassTeacher:True,
subjects:[science,Maths]},
{id:098,
name:"teacher2",
isClassTeacher:false,
subject:["social","English"]
]
}

here I want to introduce one more field “classTeacherName” in the root, and value should be from our teachers Array
output look like

{
classic : 1,
section: 'A',
classTeacherName :"teacher 1",
teachers[
{id :123,
name:"teacher 1",
isClassTeacher:True,
subjects:[science,Maths]},
{id:098,
name:"teacher2",
isClassTeacher:false,
subject:["social","English"]
]
}

I have tried with below query

db.collection.udateOne({},{$set:{"classTeacherName": {$first:"$teachers.name}}})

and I have tried many other ways. Please help me to resolve this

Hi @madhan_joe,

JSON is invalid as there are syntax errors above, please correct these in future as it will make it easier for other community members to try reproduce / import any sample documents on their own test environments when they assist you.

In saying so, I have the following in my test environment:

{
    _id: ObjectId("646d9e2e133a7d563dd508c1"),
    classic: 1,
    section: 'A',
    teachers: [
      {
        id: 123,
        name: 'teacher 1',
        isClassTeacher: true,
        subjects: [ 'science', 'Maths' ]
      },
      {
        id: 98,
        name: 'teacher2',
        isClassTeacher: false,
        subject: [ 'social', 'English' ]
      }
    ]
}

The above document after the updateOne() command:

db>db.teachers.updateOne({},[{$set:{classTeacherName:{$first:'$teachers.name'}}}])
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}

db>db.teachers.find({})
[
  {
    _id: ObjectId("646d9e2e133a7d563dd508c1"),
    classic: 1,
    section: 'A',
    teachers: [
      {
        id: 123,
        name: 'teacher 1',
        isClassTeacher: true,
        subjects: [ 'science', 'Maths' ]
      },
      {
        id: 98,
        name: 'teacher2',
        isClassTeacher: false,
        subject: [ 'social', 'English' ]
      }
    ],
    classTeacherName: 'teacher 1'
  }
]

I’ve only tested this on a single sample document briefly. If you believe it works for you please test accordingly against a larger test dataset thoroughly to verify it suits all your use case and requirements and alter / adjust it accordingly.

Please go over the following update with an aggregation pipeline documentation which may be of use.

Regards,
Jason

1 Like