2014년 12월 30일 화요일

How to group more than one array fields

db.Items_Col.aggregate([{$unwind:"$Items"},{$project:{"Items.name":1,"Items.count":1}},{$group:{"_id":"$Items.name",count:{$sum:"$Items.count"}}}])

{
    "result" : [
        {
            "_id" : "item1",
            "count" : 8
        },
        {
            "_id" : "item3",
            "count" : 6
        },
        {
            "_id" : "item4",
            "count" : 12
        }
    ],
    "ok" : 1
}

This shows item1 is purchased by 8 different persons, item3 is purchased by 6 different persons and so on , but there are some items which are common, i want to count them separately. I mean, if item1 and item4 are bought together by 3 people the it should display as below 


  {
    "result" : [
        {
            "_id" : "item1",
            "count" : 5
        },
        {
            "_id" : "item3",
            "count" : 6
        },
        {
            "_id" : "item4",
            "count" : 9
        },
        {
            "_id" : ("item1","item4")
            "count" : 3
        }
    ],
    "ok" : 1
}

Is this possible? How can I change the query? kindly help




First, you should remove "{$project:{"Items.name":1,"Items.count":1}}"
from your pipeline.  You don't need $project if you are not computing
some new field or otherwise transforming fields.

Second, could you provide a sample document - it's not clear to me
what the input looks like.

Also, what version of MongoDB are you running?




Thank you, I am using  2.4.12, 
this is how my data look like
{
    "_id" : ObjectId("54a3fd650d9f042fad630109"),
    "Amount" : 50,
    "Items" : [
        {
            "count" : 1,
            "name" : "Item1"
        }
    ],
    "cust_id" : "xyz123",
    "att_id" : 5066889,
    "cust_hash" : NumberLong("-2172629883778622831")
}
{
    "_id" : ObjectId("54a3fd650d9f042fad63010a"),
    "Amount" : 300,
    "Items" : [
        {
            "count" : 1,
            "name" : "Item2"
        },
        {
            "count" : 1,
            "name" : "Item4"
        },
    ],
    "cust_id" : "tta674",
    "att_id" : 5066901,
    "cust_hash" : NumberLong("6652206526564085472")
}
{
    "_id" : ObjectId("54a3fd650d9f042fad63010a"),
    "Amount" : 120,
    "Items" : [
        {
            "count" : 1,
            "name" : "Item8"
        },
        
    ],
    "cust_id" : "rta694",
    "att_id" : 5067902,
    "cust_hash" : NumberLong("-8024102708171490622")




I guess I'm not clear on what you mean by "bought together" - you mean
in the same document, like Item2 and Item4 are?

Should they count both separately *and* together?  Your total count
will then be higher than number of items sold.

Also, if customerA bought items 1, 2 and 3  and customerB bought items
2 and 3 - should that count as items 2&3 being bought twice together?

In your sample three documents, should the output of counts be:
Item1: 1,
Item2: 1,
Item4: 1,
Item8: 1,
(Item2&Item4): 1


댓글 없음:

댓글 쓰기