1

I have this values on my MongoDB:

enter image description here

I need to group them by date and by the value. I need to create a chart that shows when the value changed. And I need to show only if the value changed.

How can I do it in MongoDb?

My currently aggregation is like this:

 let history = await History.aggregate([
        {
            $match: {
                address: "123456",
                token_to_index: "1"
            }
        },
        {
            $group: {
                _id : {
                    date: "$date",
                    floor_price: "$stats.floor_price"
                },
                count: { $sum: 1 }
            }
        },
        { 
            $sort: { "_id.date": 1} 
        }
    ]);

I basically need this on MongoDB:

history = history.filter((item, index) => {
            if(index === 0) {
                return item;
            } else {
                if(history[index-1]._id.floor_price !== item._id.floor_price) {
                    return item;
                }
            }
    })

Thanks!

Lucas Veiga
  • 1,758
  • 7
  • 27
  • 45

1 Answers1

1

You can change your query,

  • $group by floor_price field and get max date by $max
  • $sort by date in ascending order
let history = await History.aggregate([
  {
    $match: {
      address: "123456",
      token_to_index: "1"
    }
  },
  {
    $group: {
      _id: "$stats.floor_price",
      date: { $max: "$date" },
      count: { $sum: 1 }
    }
  },
  { $sort: { "date": 1 } }
])

Playground

turivishal
  • 34,368
  • 7
  • 36
  • 59
  • I have thoughtsomething like this, however if the prices go up and down multiple times, you will only get the last time that changes, I don't think that is the expected result. – Rubén Vega Aug 10 '21 at 14:32
  • For example in this [playground](https://mongoplayground.net/p/W1fb3hr4eMb) I think that we should return the 5 documents, but mayben I'm wrong. – Rubén Vega Aug 10 '21 at 14:35