user471011
user471011

Reputation: 7364

MongoDB: How to get the oldest Document?

MongoDB collection that I have:

/* 1 */
{
    "_id" : ObjectId("5f4c93478ac8f4f9d79151bd"),
    "property" : "prop_1",
    "created" : ISODate("2020-01-01T22:00:00.000Z")
}

/* 2 */
{
    "_id" : ObjectId("5f4c93628ac8f4f9d79151be"),
    "property" : "prop_1",
    "created" : ISODate("2020-01-02T22:00:00.000Z")
}

/* 3 */
{
    "_id" : ObjectId("5f4c93708ac8f4f9d79151c0"),
    "property" : "prop_2",
    "created" : ISODate("2020-01-01T22:00:00.000Z")
}

/* 4 */
{
    "_id" : ObjectId("5f4c93738ac8f4f9d79151c1"),
    "property" : "prop_2",
    "created" : ISODate("2020-01-02T22:00:00.000Z")
}

I am in trouble with a query to get the oldest document where attribute property equals to some specific value, for example, I need to find the oldest Document where attribute property is equal prop_1:

/* 1 */
{
    "_id" : ObjectId("5f4c93478ac8f4f9d79151bd"),
    "property" : "prop_1",
    "created" : ISODate("2020-01-01T22:00:00.000Z")
}

Could you please provide any advice?

Upvotes: 1

Views: 1808

Answers (2)

mickl
mickl

Reputation: 49945

Use $match to filter by property, $sort and $limit to get the oldest one:

db.collection.aggregate([
    { $match: { property: "prop_1" } },
    { $sort: { created: -1 } }.
    { $limit: 1 }
])

Mongo Playground

Upvotes: 4

turivishal
turivishal

Reputation: 36104

You can use find() with sort and limit method,

db.collection.find({ property: "prop_1" })
.sort( { _id: -1 } ) // you can use { created: -1 }, but _id is always unique and made by timestamp
.limit(1);

Upvotes: 3

Related Questions