Home > Net >  why we use " $ " in MongoDb aggregations?
why we use " $ " in MongoDb aggregations?

Time:11-24

$lookup : {
  from: "categories",
  localField: "_id",
  foreignField: "userId",
  as: "categories_details"
}

Why we used "$" as a prefix of lookup here?

CodePudding user response:

It is the syntax of MongoDB. It is not used only in Aggregation framework, but in basic query syntax too.

Places where $ is used:
  1. Operators have the prefix of $ in theirs names - Ex: $eq, $in, $and...
  2. Stages in Aggregation framework have prefix of $ in theirs names - Ex: $set, $group, $project...
  3. In Aggregation pipeline, when you want to access the value of some field of the current document, you should use the prefix of $ with the name of that field

CodePudding user response:

$ sign in MongoDB usually refers to many things, depends where and how to use it:

  1. "$" is reserved for operators: It could be used with some operators like $gte, $in, $eq, or $lookup, this way we're telling mongo to treat next expression according to that operator prefixed with $ sign.

  2. "$field-name": If $ sign was used inside a string with a field name, the $ in this case is referred to the root document field, for example:

    { "$sum": { "$map": { "input": "$data", "as": "currentData", "in": { "$size": "$$currentData.d" } } } }

Here '$data' is the document array field.

  1. "$$variable": Sometimes $ sign can be used to refer to variables, so according to previous code, "$$currentData" is the variable taken in the as expression of $map aggregation.

  2. $ (update): The positional $ operator identifies an element in an array to update without explicitly specifying the position of the element in the array. You can read more about this here

  3. $ (projection): The positional $ operator limits the contents of an to return the first element that matches the query condition on the array. You can read more about this here

  • Related