when should we use “$” sign in front of a collection’s field names in aggregation pipelines?
It’s very confusing.
HI @farideh_gorji,
You have to use the $
sign every time you want to access the value of a field in the document that was passed to that stage.
Suppose you have the following document that is storing some user data:
{
"name": {
"first": "Sourabh",
"last": "Bagrecha"
},
"email": "sourabh@example.com",
"phone": "1234567890",
"address": {
"street": "123 Main St",
"city": "New York",
"state": "NY",
"zip": "10001"
}
}
So if you want to get the full name of every user, you can achieve that using the following aggregation pipeline syntax:
[
{
"$project": {
"fullName": {
"$concat": ["$name.first", " ", "$name.last"]
}
}
}
]
You can see how we utilized the $
to access the value of a field from the document.
If you have any doubts, please feel free to reach out to us.
Thanks and Regards.
Sourabh Bagrecha,
MongoDB
2 Likes
This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.