Use of $ with <field>

It’s very confusing for me to understand where to use field and where $ field
Can you please explain?

There are 2 scenarios,

Ex 1: $project, $match, etc.
Ex 2: $split, $sum, $avg, $max, $min, etc.

  • expressions:
    • when you are doing some kind of operation on existing fields that you have in document then you have to use an expression operation, so how expression operators will choose this is existing field? or you passed string, that time you have to pass $ so expression operators will know this is an reference field that is already exist in document.

Sample Document:
{ "_id": ObjectId("xxxxxxxx"), "years": [2017,2019,2020,2018] }

Ex 3: Find maximum year form years field.
Query would be:
{ $project: { years: { $max: "$years" } } }

We are referring years field to $max operator, using $ reference to $years.

Ex 4: Find document that contain 2020 year in years field.
Query would be:
{ $match: { years: 2020 } }

We have outer value 2020 and we are checking condition whiteout expression, here no need to specify $ sign.

1 Like

Thank you!!

@Shrikrushna_Upakare, Check this one too - What does a dollar sign mean in mongodb in terms of groups? - Stack Overflow

Thanks Shravan

@Shrikrushna_Upakare because repeating is not too bad:

If you’re just getting started with MongoDB:

  • use $ to access field values

And then for stages and operators.


db.coll.find({$expr:{$eq:["$field1", 5]}})

You can also use “$field2” instead of 5, and point to another field. And you can access subfields like "$field1.stop".

Equivalent using aggregation

db.coll.aggregate({ $match:{$expr:{$eq:["$field1", 5] }}})

For stages other than $match (most of them), you don’t need $expr. Indeed, find() provides same functionality than $match.

$ provides much more. But when you are learning sometimes less is more. So I provide a minimum most common use.

Sure. Thanks @Santiago_Miranda