Mongo DB aggregation on array

Viewed 30

im trying to add element to array in document MongoDB collection with Aggregate (not regular update) match to specific name but i dont find the right syntax

for example:

{"name":"TEST1","department":"T1","skills":["JS","HTML"],"expY":5}
{"name":"TEST2","department":"T2","skills":["Java","CSS"],"expY":3}

i want to add to skills array "CSS" i try with sort, match, group, project, ($add, $push etc) and none of those syntax not working

db.collection.aggregate([ 
   { $match : { name : "TEST1" } },
   HERE I DONT KNOW WHAT IS THE RIGHT SYNTAX TO ADD ELEMENT TO skills array
])
1 Answers

If I am understading your question correctly, you want to match all the documents with name "TEST1" and then add "CSS" to the skills array. If that's correct, here is one way to do that:

db.collection.aggregate([
  {
    $match: {
      name: "TEST1"
    }
  },
  {
    $project: {
      name: "$name",
      department: "$department",
      expY: "$expY",
      skills: {
        $concatArrays: [
          "$skills",
          [
            "CSS"
          ]
        ]
      }
    }
  }
])

Playground

Here is how to update your document to add "CSS" to the array:

db.your_collection.update({ name : "TEST1" }, { $push: { skills: 'CSS' } })
Related