Shashi Tunga
Shashi Tunga

Reputation: 516

When to prefix attribute name with $ in Mongo db aggregate function.?

db.SHIPMENT.aggregate([{$match:{'WNAME':'R group'}},
{$lookup:{"from":"PART","localField":"PNO","foreignField":"PNO","as":"parts"}},
{$unwind:"$parts"},
{$project:{"PARTS":"$parts","_id":0}}])

db.SHIPMENT.aggregate([{$group:{"_id":"$WNAME",total:{"$sum":"$QUANTITY"}}}])

full code: https://github.com/VikasNS/RIT-5th-sem-DBMS/blob/master/A42.js

  1. In the aggregate function:

    {$match:{'WNAME':'R group'}

In this WNAME does have prefix of $

But

{$unwind:"$parts"},

parts has a $ in its prefix.

2 nd query

total:{"$sum":"$QUANTITY"}}

QUANTITY HAS A $ prefix.

So, When to have $ prefix and when not to.?

Upvotes: 0

Views: 510

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311835

Use the $ prefix whenever you're providing a field name as the value in an object (i.e. to the right of the colon).

The exception being where the field can only be the name of a field, as in the localField and foreignField fields of a $lookup object.

Upvotes: 1

Related Questions