Ch1 Lab2 Computing Fields: why aggregation doesn't work?

I’m trying to make an aggregation, but it fails with error “unknown top level operator: $eq”. What am I doing wrong?
db.movies.aggregate([{$match: {$eq: [{$size: {$split: ["$title", " "]}}, 1]}}])
The logics is that I’m trying to match all documents, that have size of splitted by " " symbol field named “title” equal to 1 (means have just one word in it).

P.S. Changed query’s logic and made it work with two stages, but still I would like to understand, why I can’t just make one $match query.

Hey @Rouslan_62970

You have just used an aggregation operator in the place of where you should use a query operator.

The following links will helps show how the $eq looks and acts the same but requires different syntax

This gets a lot of students including me when I started.


@natac13, thanks a lot for the reply!

Just now I’ve tried to make a query again (not for the task, just want to get properly the topic), end up with this: db.movies.aggregate([{$match: {{$size: {$split: ["$title", " "]}}: {$eq: 1}}}]), but it still gives the error “invalid property id …”, which I believe because I can’t use an expression as a field, so I can’t make {some_expression}: {$eq: 1}. How should I do instead? As in this example I would like to choose all the documents, where an expression on some field equals to 1.

Hey @Rouslan_62970

Please review the docs for $match

$match takes a document that specifies the query conditions. The query syntax is identical to the read operation query syntax; i.e. $match does not accept raw aggregation expressions. Instead, use a $expr query expression to include aggregation expression in $match .

Therefore $match doesn’t take aggregate expression. It take query operators. Which looking at my first post will show the difference. UNLESS you use $expr

1 Like