0

I have document schema such as

{
    "_id" : 18,
    "name" : "Verdell Sowinski",
    "scores" : [
            {
                    "type" : "exam",
                    "score" : 62.12870233109035
            },
            {
                    "type" : "quiz",
                    "score" : 84.74586220889356
            },
            {
                    "type" : "homework",
                    "score" : 81.58947824932574
            },
            {
                    "type" : "homework",
                    "score" : 69.09840625499065
            }
    ]
}

I have a solution using pull that copes with removing a single element at a time but saw I want to get a general solution that would cope with irregular schema where there would be between one and many elements to the array and I would like to remove all elements based on a condition.

I'm using mongodb driver 3.2.2 and saw this pullByFilter which sounded good

Creates an update that removes from an array all elements that match the given filter.

I tried this

Bson filter = and(eq("type", "homework"), lt("score", highest));
Bson u = Updates.pullByFilter(filter);
UpdateResult ur = collection.updateOne(studentDoc, u);

Unsurprisingly, this did not have any effect since I wasn't specifying the array scores

I get an error

The positional operator did not find the match needed from the query. Unexpanded update: scores.$.type

when I change the filter to be

Bson filter = and(eq("scores.$.type", "homework"), lt("scores.$.score", highest));

Is there a one step solution to this problem?

There seems very little info on this particular method I can find. This question may relate to How to Update Multiple Array Elements in mongodb

  • This is a well known question from the M101 course material in MongoDB University offered courses. The intention of presenting this problem in the course is that you are meant to "think" about how to solve the problem, and **not** simply post a question on Stack Overflow asking someone to answer it for you. Nor is it desirable to have a source of answer that anyone can just "look up". The course material will reveal the answer to the problem when the unit is complete, so you will be given a solution. However it is desirable yo remove this post and do not further post course content. – Neil Lunn Nov 05 '17 at 07:43

1 Answers1

-2

After some more "thinking" (and a little trial and error), I found the correct Filters method to wrap my basic filter. I think I was focusing on array operators too much.

I'll not post it here in case of flaming.

Clue: think "matches..." (as in regex pattern matching) when dealing with Filters helper methods ;)

  • Posting the answer to your own question is encouraged, and certainly not, "flaming". It's far preferred to giving "clues". It seems like you may be responding to the commend on the original question, in which case their suggest to remove the post is far more appropriate. – Thomas Jan 17 '21 at 23:09