2

I'm using mongo 2.2.3 and the java driver. My dilemma, I have to $push a field and value into an array element, but I cant seem to figure out how to do this. A sample of my data:

"_id" : 1,
"scores" : [
    {
        "type" : "english",
        "score" : 78.97979
    },
    {
        "type" : "spanish",
        "score" : 6.99
    }
]

I want to push one array attribute ("grade" : "A") in document where type = english.

after push document look like this :

"_id" : 1,
    "scores" : [
        {
            "type" : "english",
            "score" : 78.97979,
            "grade" : "A"
        },
        {
            "type" : "spanish",
            "score" : 6.99
        }
    ]

I tried using shell :

db.Sample.update({"scores.type" : "english"},{"$push" : {"scores": {"grade":"A"}}})

But this is not adding attribute on specific position.

2
  • Did you try my solution? Commented Feb 20, 2015 at 8:10
  • @gasparms, Yes, i tried and solved my problem. Commented Feb 20, 2015 at 10:34

1 Answer 1

2

Try this update with Set and reference:

db.Sample.update({"scores.type" : "english"},{"$set" : {"scores.$.grade":"A"}})
Sign up to request clarification or add additional context in comments.

2 Comments

Hello, @gasparms can you differentiate $set and $push ??
Maybe you want to know differences between $push and $addToSet? Becasue, $set and $push are totally differentes. $set replace the value of field and $push append a value to an array.

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.