MongoDB:如何获取最旧的文档?

xytpbqjk  于 2023-01-01  发布在  Go
关注(0)|答案(2)|浏览(122)

我拥有的MongoDB集合:

/* 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")
}

我在查询属性property等于某个特定值的最旧文档时遇到了麻烦,例如,我需要查找属性property等于prop_1的最旧文档:

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

你能提供一些建议吗?

wdebmtf2

wdebmtf21#

使用$matchproperty$sort$limit进行过滤,以获得最旧的一个:

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

Mongo Playground

gev0vcfq

gev0vcfq2#

您可以将find()sortlimit方法一起使用,

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);

相关问题