Pierre R-A
Pierre R-A

Reputation: 529

How to find all latest distinct tuples in MongoDB/Mongoose

I've got a collection called Market where I store prices for items. Every so often, I update the value for an item. In order to keep track of all prices, I insert a new tuple each time a price for an item is changed.

My question is: how do I get the list of distinct items with the last updated price?

Example Current collection

[
  { item: 'A', timestamp: '1513555200', price: 10 },
  { item: 'B', timestamp: '1513555200', price: 50 },
  { item: 'C', timestamp: '1513555200', price: 30 },
  { item: 'A', timestamp: '1513814400', price: 14 },
  { item: 'B', timestamp: '1513814400', price: 55 },
  { item: 'A', timestamp: '1514050995', price: 15 },
  { item: 'D', timestamp: '1514050995', price: 150 },
] 

Desired result:

[
  { item: 'A', timestamp: '1514050995', price: 15 },
  { item: 'B', timestamp: '1513814400', price: 55 },
  { item: 'C', timestamp: '1513555200', price: 30 },
  { item: 'D', timestamp: '1514050995', price: 150 }
]

Upvotes: 2

Views: 696

Answers (1)

Pierre R-A
Pierre R-A

Reputation: 529

Looking into the documentation, I've found the operator $first which provide a example solving my question.

db.market.aggregate([
  { $sort: {item: 1, timestamp: -1} },
  { $group: {
    _id: "$item",
    timestamp: {$first: "$timestamp"},
    price: {$first: "$price"}
  }}
]);

Upvotes: 2

Related Questions