Create price range edge in mongodb aggregation pipeline

My document structure looks like this

{
title : 'a product',
price : 10
}

      

What I would like to do is have a dynamic price range that would look like

[
        {
            facet : '0-30',
            count : 5
        },
        {
            facet : '30-100',
            count : 40
        }
]

      

Obviously there will be a fixed interval like 50. I have used ElasticSearch for this using the histogram function, but I cannot get it to work in mongo. I'm guessing it might be possible to make the map shrink to do this, but I'm wondering if there is a way to add aggregation to my pipeline.

+3


source to share


1 answer


You can try an aggregation pipeline where you can design a field facet

using an operator.To demonstrate this, let's say you have a collection with the following docs: $cond

db.collection.insert([
    { "title" : "Product STU", "price" : 10 },
    { "title" : "Product XYZ", "price" : 50 },
    { "title" : "Product PCT", "price" : 14 },
    { "title" : "Product DEF", "price" : 89 },
    { "title" : "Product DYQ", "price" : 34 },
    { "title" : "Product ABC", "price" : 40 },
    { "title" : "Product JKL", "price" : 50 },
    { "title" : "Product PQR", "price" : 75 },
    { "title" : "Product MNO", "price" : 81 },
    { "title" : "Product VWN", "price" : 5 },
    { "title" : "Product KLM", "price" : 63 }
]);

      

The aggregation pipeline that will achieve the desired result looks like this:



db.collection.aggregate([
    {
        "$match": {
            "price": { "$lte": 100, "$gte": 0 }
        }
    },
    {
        "$project": {
            "title": 1,
            "price": 1,
            "_id": 0,
            "facet": {
                "$cond": [ { "$gte": [ "$price", 30 ] }, "30-100", "0-30" ]
            }
        }
    },
    {
        "$group": {
            "_id": "$facet",
            "count": {
                "$sum": 1
            }
        }
    },
    {
        "$project": {
            "facet": "$_id",
            "_id": 0,
            "count": 1
        }
    }
])

      

Output

/* 1 */
{
    "result" : [ 
        {
            "count" : 8,
            "facet" : "30-100"
        }, 
        {
            "count" : 3,
            "facet" : "0-30"
        }
    ],
    "ok" : 1
}

      

+1


source







All Articles