Jona Becher
Jona Becher

Reputation: 35

$sum a field in an array - Query that results documents above a certain value

I created the following schema :

const videoSchema = createSchema(
    link: Type.string({required: true}),  
    description: Type.string({required: true}),
    answers: Type.array({required: true}).of({
         text: Type.string(), 
         likes: Type.number()
    })
);
export const videoModel = typedModel('video', videoSchema);

Now I want to write a query that only has videos with over 200 likes as a result. I've tried to work with .aggregate, $reduce and $sum, but I can't get it to work.

Does anyone know how to achieve this ? Thank you in advance!

Upvotes: 2

Views: 48

Answers (1)

whoami - fakeFaceTrueSoul
whoami - fakeFaceTrueSoul

Reputation: 17925

You can try below query :

db.collection.aggregate([
/** Add a field which holds count of likes for all answers for a video */
{
    $addFields: {
        likesCount: {
            $reduce: {
                input: "$answers.likes",
                initialValue: 0,
                in: {
                    $add: [
                        "$$value",
                        "$$this"
                    ]
                }
            }
        }
    }
},
/** filter to retain videos whose likes > 200 */
{
    $match: {
        likesCount: {
            $gt: 200
        }
    }
},
/** Remove additional field from documents */
{
    $project: {
        likesCount: 0
    }
  }
])

Test : MongoDB-Playground

Upvotes: 1

Related Questions