1

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 Answer 1

1

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' } })
Sign up to request clarification or add additional context in comments.

2 Comments

thank you for the answer its show that is work but! when i run this query its not really change the array its show me the original array when i look on compass / db.collection.find()
@Carnjaxxofficial Aggregation is not used for updates. You need the simple update command. I have updated my answer to show you how to do that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.