ink*_*iti 90 mongodb mongodb-query
我想知道一个集合中的最新记录.怎么做?
注意:我知道以下命令行查询有效:
1. db.test.find().sort({"idate":-1}).limit(1).forEach(printjson);
2. db.test.find().skip(db.test.count()-1).forEach(printjson)
Run Code Online (Sandbox Code Playgroud)
其中idate添加了时间戳.
问题是收集是时候收回数据的时间越长,我的"测试"集合真的非常庞大.我需要一个具有恒定时间响应的查询.
如果有任何更好的mongodb命令行查询,请告诉我.
Dig*_*its 120
这是对前一个答案的重复,但它更可能适用于不同的mongodb版本.
db.collection.find().limit(1).sort({$natural:-1})
Run Code Online (Sandbox Code Playgroud)
dar*_*uby 29
这将为您提供最后一个文件 collection
db.collectionName.findOne({}, {sort:{$natural:-1}})
Run Code Online (Sandbox Code Playgroud)
$natural:-1 表示插入记录的顺序相反的顺序.
编辑:对于所有的downvoters,上面是Mongoose语法,mongo CLI语法是:db.collectionName.find({}).sort({$natural:-1}).limit(1)
Gat*_* VP 20
我需要一个具有恒定时间响应的查询
默认情况下,MongoDB中的索引是B-Trees.搜索B树是O(logN)操作,因此甚至find({_id:...})不会提供恒定时间O(1)响应.
这就是说,您也可以按照_id您使用ObjectId的ID进行排序.详情请见此处.当然,即便如此,直到最后一秒也是如此.
你可以诉诸"写两次".一次写入主集合并再次写入"最后更新"集合.如果没有交易,这将不是完美的,但只有一个项目在"最后更新"的集合中,它总是很快.
iva*_*ncz 10
从MongoDB集合中获取最后一个项目的另一种方式(不必介意示例):
> db.collection.find().sort({'_id':-1}).limit(1)
Run Code Online (Sandbox Code Playgroud)
法线投影
> db.Sports.find()
{ "_id" : ObjectId("5bfb5f82dea65504b456ab12"), "Type" : "NFL", "Head" : "Patriots Won SuperBowl 2017", "Body" : "Again, the Pats won the Super Bowl." }
{ "_id" : ObjectId("5bfb6011dea65504b456ab13"), "Type" : "World Cup 2018", "Head" : "Brazil Qualified for Round of 16", "Body" : "The Brazilians are happy today, due to the qualification of the Brazilian Team for the Round of 16 for the World Cup 2018." }
{ "_id" : ObjectId("5bfb60b1dea65504b456ab14"), "Type" : "F1", "Head" : "Ferrari Lost Championship", "Body" : "By two positions, Ferrari loses the F1 Championship, leaving the Italians in tears." }
Run Code Online (Sandbox Code Playgroud)
排序投影(_id:倒序)
> db.Sports.find().sort({'_id':-1})
{ "_id" : ObjectId("5bfb60b1dea65504b456ab14"), "Type" : "F1", "Head" : "Ferrari Lost Championship", "Body" : "By two positions, Ferrari loses the F1 Championship, leaving the Italians in tears." }
{ "_id" : ObjectId("5bfb6011dea65504b456ab13"), "Type" : "World Cup 2018", "Head" : "Brazil Qualified for Round of 16", "Body" : "The Brazilians are happy today, due to the qualification of the Brazilian Team for the Round of 16 for the World Cup 2018." }
{ "_id" : ObjectId("5bfb5f82dea65504b456ab12"), "Type" : "NFL", "Head" : "Patriots Won SuperBowl 2018", "Body" : "Again, the Pats won the Super Bowl" }
Run Code Online (Sandbox Code Playgroud)
sort({'_id':-1}),根据所有文档的_ids 降序定义投影。
排序投影(_id:反向顺序):从集合中获取最新(最后)文档。
> db.Sports.find().sort({'_id':-1}).limit(1)
{ "_id" : ObjectId("5bfb60b1dea65504b456ab14"), "Type" : "F1", "Head" : "Ferrari Lost Championship", "Body" : "By two positions, Ferrari loses the F1 Championship, leaving the Italians in tears." }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
118652 次 |
| 最近记录: |