Error $split in Compass

Hi,

At the Computing Fields lab, they tell you to look at $split. I am trying to do it with Compass and I am getting an error, I don’t know what I am doing wrong in the formula.

Attached is a screen dump, thanks in advance

Carles

See the documentation at https://docs.mongodb.com/manual/reference/operator/aggregation/split/.

You will find the following full example that uses $project:

db.deliveries.aggregate([
  { $project : { city_state : { $split: ["$city", ", "] }, qty : 1 } },
  { $unwind : "$city_state" },
  { $match : { city_state : /[A-Z]{2}/ } },
  { $group : { _id: { "state" : "$city_state" }, total_qty : { "$sum" : "$qty" } } },
  { $sort : { total_qty : -1 } }
]);

Thanks Steeve, I had already seen the example. My question is putting only $split shouldn’t it work in Compass?

No it should not. What ever the tool, what ever the language you use, the syntax is the same. The gui helps you because you can select $project from the list and it puts the enclosing braces for you. But inside the braces it has to be the same. So in this case rather than

$split : [ "$title" , " " ]

you need to do

"splitted_title" : { "$split" : [ "title" , " " ] }

You could use title in place of splitted_title if you want to override the original.

1 Like

Interesting question @Carles_Barbal !

I believe @steevej points out that a field to store $split is needed. At least this is the behavior inside $project.

So I’ll give you some context on this.


Syntax

The syntax of operators is dependant on the stage you’re running the command. Luckily, some stages quite similar like $addFields and $project, and they work similarly with $operators. But these are different from how $match stage uses $operators.

So, many $operators calls depend on which $stage you are working on, and most are not available in all stages.

For example, we could not use $unwind:{$split:...}. This stage expects a <fieldpath> and not an <expression>

Problem

The syntax for split is what you typed, but we also need the “main level operator” $project. This stage blueprint is something like this {$project:{field:expression}}, a concrete example following up on steevej comment:

city_state:{$split...}

You don’t need to add the $project in Compass because it is already selected (From my understanding of the picture, I don’t use compass).

Thank you for stevej response and the clarification from santimir

1 Like