user4673965
user4673965

Reputation:

Mongodb: keeping a limited amount of data of a sorted array

I have a document data of documents (containing readings) for each item in my collection:

{
    "_id": ...,
    "data": {
        "2016-07-24": {"reading1": 1},
        "2016-07-25": {"reading1": 2},
        "2016-07-26": {"reading1": 3}
    }
}

Data is added periodically with the same format.

The keys must be unique, as new data will replace old data (for example, "2016-07-25": {"reading1": 9} would replace the value listed above)

How do I keep only the most recent 10 entries (when keys are sorted)? Can I do this with a mongo query or should I use application-side logic?

Turning data into an array could work, but has the issue of having entries with duplicate dates.

Thanks for your help!

Upvotes: 0

Views: 94

Answers (1)

helmy
helmy

Reputation: 9497

The $slice array update operator does exactly what you're asking. Take a look at the examples on the doc page.

Upvotes: 1

Related Questions