0

I have the following scheme on my MongoDB

{
    "weekday": 0,
    "hour":[
            {
                "hour": 14,
                "user": "user",
                "promoted": ["user1","user2","user3","user4"]
            },
            {
                "hour": 15,
                "user": "user",
                "promoted": ["user1","user2","user3","user4"]
            },
    ]
}

I want to add single elements to the "promoted" array of a certain hour, for example, add "user5" to the "promoted" array of the sub-document which has "hour": 14.

I have learned how to add new sub-documents to the hour array but not how to add a single element to the "promoted" array of a already existing sub-document. How could I do that?

1

1 Answer 1

0

In this case you need use $. Look here the documentation: https://docs.mongodb.com/manual/reference/operator/update/positional/

However, try this script:

db.yourCollection.update(
  {
    "hour.hour": 14
  },
  {
    $push: {"hour.$.promoted": "user5"}
  }
)

Result

{
    "_id" : ObjectId("60bb8e166cfda8327bbe08eb"),
    "weekday" : 0.0,
    "hour" : [ 
        {
            "hour" : 14.0,
            "user" : "user",
            "promoted" : [ "user1", "user2", "user3", "user4", "user5"]
        }, 
        {
            "hour" : 15.0,
            "user" : "user",
            "promoted" : ["user1", "user2", "user3", "user4"]
        }
    ]
}
Sign up to request clarification or add additional context in comments.

2 Comments

please don't post answer when you see any duplicate question comment in question, there are lots of similar questions. see same answer like your.
@turivishal ok, sorry. I am a new contributor :D

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.