Laxman Singh Garia
Laxman Singh Garia

Reputation: 73

what does $ do with fields when aggregating in mongodb

db.cata.aggregate([{"$unwind":"$review"},{$group:{_id:"review",cnt:{$sum:1}}}]).pretty()

db.cata.aggregate([{"$unwind":"$review"},{$group:{_id:"$review",cnt:{$sum:1}}}]).pretty()

what these two queries do in document..how $review and review do...how $ works with fields...

my document is

{
"_id" : ObjectId("56dd01bdf3b660327b932da1"),
"product" : "super",
"price" : 10,
"review" : [
    {
        "user" : "fred",
        "comment" : "great",
        "rating" : 10
    },
    {
        "user" : "tom",
        "comment" : "i agree",
        "rating" : 3
    },
    {
        "user" : "vin",
        "comment" : "good",
        "rating" : 9
    },
    {
        "user" : "anubhav",
        "comment" : "too good",
        "rating" : 8
    }]
}

Upvotes: 6

Views: 1188

Answers (2)

Saleem
Saleem

Reputation: 8978

$ fields in front of fields tell aggregation framework that inject actual value of field during execution.

e.g. in your case.

db.cata.aggregate([{"$unwind":"$review"} $review will be replaced by contents of review field which is

{
    "user" : "fred",
    "comment" : "great",
    "rating" : 10
}
...

But you really need to read documentation. It's much easier than writing questions here on Stack Overflow.

Upvotes: 3

zangw
zangw

Reputation: 48396

Per the Mongodb doc said

The operand is a field path:

{ $unwind: <field path> }

To specify a field path, prefix the field name with a dollar sign $ and enclose in quotes.

Upvotes: 3

Related Questions