When to $ and when not to $

I’m a little confused about when it is necessary to include the $ symbol on a field name and when not to. All of the aggregation stage names (e.g.: $match) and operations (e.g.: $in) have it which makes sense, but I have to try a few different times to get the convention right on variables. I feel like this might have been in one of the lectures but didn’t stick in my brain. Thanks!

1 Like

You’re not the only one. My understanding so far is that including a $ in front of a field name makes it a field path expression.

I think where you want to reference a field on the right hand side of a key: value pair in JSON, including the $ tells Mongo that it’s the path to a field rather than a literal string, and therefore it’s the contents of that field rather than its name that you want Mongo to work with. For example…

    $bucket: {
      groupBy: '$imdb.rating',

We can’t group by the literal string “imdb.rating” because that doesn’t make any sense. But we can group by the field path ‘$imdb.rating’, because that gives Mongo the path to the field in our documents that we want to group by.

This is probably a gross over-simplification and I’m sure the experts can explain it better than this humble student can :slight_smile:

Oh, and I’ve just learned that if I want a dollar symbol to appear on its own in a forum post, I need to type a backslash before the dollar symbol.

1 Like

Thanks Simon! After working through some more of the labs I’m starting to get an intuition for it, and I think your description is spot on.

Nice tip with including $ in a post too! haha