1

I have a document like this one:

{
        "_id" : 0,
        "name" : "aimee Zank",
        "scores" : [
                {
                        "type" : "exam",
                        "score" : 1.463179736705023
                },
                {
                        "type" : "quiz",
                        "score" : 11.78273309957772
                },
                {
                        "type" : "homework",
                        "score" : 6.676176060654615
                },
                {
                        "type" : "homework",
                        "score" : 35.8740349954354
                }
        ]
}

On that document I want to delete the score that has the lowest score of type homework. First, I'm trying to do it on the mongo shell, so I put the values manually.

 db.students.update({ _id:0}, {$unset: {"scores.score":6.676176060654615} })

That query does nothing, so I tried to search on Google and I found here a question about removing an object from an array and I tried this other query:

db.students.update({ _id:0 }, { $unset: 
                                   { "scores": { 
                                        "homework": 6.676176060654615 } } }, false, true);

The second query worked, but not as I expected because the result was

{ "_id" : 0, "name" : "aimee Zank" }

To check that the lowest value of type homework exists I find with this query:

db.students.find({"scores.score":6.676176060654615}).pretty();

1 Answer 1

1

If you want to delete/pull only score = 6.676176060654615, you need to simply use following query :

db.collection.update({"_id":0},{"$pull":{"scores":{score: 6.676176060654615}}})

If you want to find minimum value and remove it from your collection. You need to do this is two steps. For more details refer this

Sign up to request clarification or add additional context in comments.

3 Comments

This should work to pull score = 6.676176060654615 . can you check using find query whether score = 6.676176060654615 exists or not?
I edited my question and I added the find that I used to check if exists. Using $min can I get the minimum score of type homework?
I tried again with the query you provied, because it is similar to one from the link you posted.

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.