【mongoDB】mongoDB 查看表中的最近10条数据

2023-06-06  本文已影响0人  Bogon

mongoDB如何查看表中的最近10条数据 ?

在MongoDB中,可以使用find()方法查询表中的数据,并使用sort()方法对数据进行排序,然后使用limit()方法限制查询结果的数量。

以下是查看表中最新10条数据的语句:

> use  testDB
> db.collection.find().sort({_id: -1}).limit(10)

其中,collection是指要查询的表的名称,_id: -1表示按照_id字段进行倒序排序,即最新的数据排在前面,limit(10)表示只查询前10条数据。

如果我想要插入到 MongoDB 的fs.files 表中下面这条数据,如果操作?

{
        "_id" : ObjectId("3eae322b6050455c09acf233"),
        "filename" : "filename.rar",
        "aliases" : null,
        "chunkSize" : NumberLong(261120),
        "uploadDate" : ISODate("2023-06-01T03:55:53.273Z"),
        "bizkey" : "file",
        "length" : NumberLong(3576997),
        "networkId" : "61xxxxxxx08e7a270c1b7025",
        "contentType" : "application/x-rar-compressed",
        "userId" : "61b813b4dxxxxx840aa3a63a",
        "md5" : "3d9530b6307dd25xxxxx62064bea8fdd",
        "lastVisitTime" : ISODate("2023-06-01T07:24:52.743Z"),
        "visitCnt" : 1
}

如果你想要插入一个新的文档到 fs.files 集合中,那么 _id 字段是可以不用指定的,MongoDB 会自动生成一个唯一的 _id 值。

如果你需要插入一个指定 _id 值的文档,可以在插入文档时将 _id 字段设置为指定的值,如下所示:

db.fs.files.insertOne({
        "_id" : ObjectId("3eae322b6050455c09acf233"),
        "filename" : "filename.rar",
        "aliases" : null,
        "chunkSize" : NumberLong(261120),
        "uploadDate" : ISODate("2023-06-01T03:55:53.273Z"),
        "bizkey" : "file",
        "length" : NumberLong(3576997),
        "networkId" : "61xxxxxxx08e7a270c1b7025",
        "contentType" : "application/x-rar-compressed",
        "userId" : "61b813b4dxxxxx840aa3a63a",
        "md5" : "3d9530b6307dd25xxxxx62064bea8fdd",
        "lastVisitTime" : ISODate("2023-06-01T07:24:52.743Z"),
        "visitCnt" : 1
})

如果指定的 _id 值已经存在于集合中,那么插入操作会失败并提示 _id 值重复。如果你需要更新一个已经存在的文档,可以使用 updateOne()replaceOne() 方法,其中 updateOne() 方法用于更新指定字段,replaceOne() 方法用于替换整个文档。

注意,如果要将文件上传到MongoDB的GridFS中,还需要使用MongoDB的uploadStream()方法将文件内容上传到fs.chunks表中,具体可以参考MongoDB的官方文档。

上一篇 下一篇

猜你喜欢

热点阅读