Mongodb grouping and return all result

Viewed 39

I want to be able to group the documents only if these documents contains same cartId. For example, my order collection look like this(adding cartId field only when user checkout from cart page otherwise no field for cartId(ie empty))

{orderId:1234, qty:1,price:10}
{orderId:1235, qty:1,price:10,cartId:111}
{orderId:1236, qty:3,price:30,cartId:111}
{orderId:1237, qty:2,price:20}

here I want to group the documents having same cartId but don't group the documents having no cartId but it must be in query result as a separate entities. The query result should look like this

[
    {orderId:1234, qty:1,price:10} //no cartId
    {orderId:111,qt:4,price:40},//grouped two documents and putted orderId as cartId , sum up qty and price 
    {orderId:1237, qty:2,price:20},//no cartId
]

Thanks in advance

1 Answers

What about $facet stage? It can process the same documents with different pipelines. Would this work for you?

p1=[
            {
                $match: {cartId: {$ne: null}}
            },{
                $group: {
                  _id: {cartId: "$cartId"},
                  sumPrice: {  $sum: '$price' },
                  sumQty: { $sum: '$qty' }
                }
            }
        ];
p2= [{ $match: {cartId:  null} }];
 
db.col.aggregate([{
    $facet: {
        grouped_by_cartId: p1,
        no_cartId: p2
        }
    }
    ]);

Result:

{
    "grouped_by_cartId" : [
        {
            "_id" : 101,
            "sumPrice" : 45,
            "sumQ" : 5
        }
    ],
    "no_cartId" : [
        {
            "_id" : ObjectId("609be349adce920463621d9c"),
            "orderId" : 1234,
            "qty" : 1,
            "price" : 10
        },
        {
            "_id" : ObjectId("609be349adce920463621d9f"),
            "orderId" : 1237,
            "qty" : 2,
            "price" : 20
        }
    ]
}
Related