$addFields in Mongo Aggregation

Write a query in mongo to use of $addFields  in Mongo


Example:

[{ 
        "_id" : ObjectId("6024b764abea6cc5c99ceefd")
        "name" : "George"
        "grade" : 5.0
        "school" : "MathHighSchool"
    }
    { 
        "_id" : ObjectId("6024b764abea6cc5c99ceefe")
        "name" : "John"
        "grade" : 4.0
        "school" : "MathHighSchool"
    }
    { 
        "_id" : ObjectId("6024b764abea6cc5c99ceeff")
        "name" : "Paul"
        "grade" : 3.0
        "school" : "MathHighSchool"
    }
    { 
        "_id" : ObjectId("6024b764abea6cc5c99cef00")
        "name" : "Ringo"
        "grade" : 5.0
        "school" : "MathHighSchool"
    }
    { 
        "_id" : ObjectId("6024b764abea6cc5c99cef01")
        "name" : "Johnny"
        "grade" : 2.0
        "school" : "MathHighSchool"
    }
    { 
        "_id" : ObjectId("6024b764abea6cc5c99cef02")
        "name" : "Joshua"
        "grade" : 7.0
        "school" : "MathHighSchool"
    }


]

Approach

Query: Query to add one more field class to all document.

db.getCollection("people").aggregate([
  {
     $addFields: {
        "class""10th"
     }
  }
] )

    

Output: 

[
   
  "_id" : ObjectId("6024b764abea6cc5c99ceefd")
  "name" : "George"
  "grade" : 5.0
  "school" : "MathHighSchool"
  "class" : "10th"
}
  "_id" : ObjectId("6024b764abea6cc5c99ceefe")
  "name" : "John"
  "grade" : 4.0
  "school" : "MathHighSchool"
  "class" : "10th"
}
  "_id" : ObjectId("6024b764abea6cc5c99ceeff")
  "name" : "Paul"
  "grade" : 3.0
  "school" : "MathHighSchool"
  "class" : "10th"
}
  "_id" : ObjectId("6024b764abea6cc5c99cef00")
  "name" : "Ringo"
  "grade" : 5.0
  "school" : "MathHighSchool"
  "class" : "10th"
}
  "_id" : ObjectId("6024b764abea6cc5c99cef01")
  "name" : "Johnny"
  "grade" : 2.0
  "school" : "MathHighSchool"
  "class" : "10th"
}
  "_id" : ObjectId("6024b764abea6cc5c99cef02")
  "name" : "Joshua"
  "grade" : 7.0
  "school" : "MathHighSchool"
  "class" : "10th"
}

]


No comments:

Post a Comment