简体   繁体   English

在MongoDb中,有一种方法可以从多个文档中获取最后1000个数组元素

[英]In MongoDb is there a way to get last 1000 array elements from multiple documents

Given the following Mongo document model: 给定以下Mongo文档模型:

文件模型

Each document in the collection represents 1 hour of resource monitoring. 集合中的每个文档代表1个小时的资源监视。 In each document, there is a collection of summaries. 在每个文档中,都有摘要的集合。 There is also a count of the number of summaries as an integer, as it may make life easier. 还可以将摘要的数量记为整数,因为它可以使生活更轻松。

Is there an efficient way to query the collection and return either just the recent most 1000 summaries as an aggregated list? 有没有一种有效的方法来查询集合并仅返回最近的1000个摘要作为聚合列表?

Or an efficient way to query the collection and return the number of documents that contain the recent most 1000 summaries? 还是一种有效的方法来查询集合并返回包含最近的1000个摘要的文档数?

The number of summaries in each document will differ, but the number of summaries in one single document will never equal more than 1000. 每个文档中的摘要数量将有所不同,但是一个文档中的摘要数量绝不能超过1000。

EDIT: I should mention I am using mongo with the .NET driver so have LINQ available to me. 编辑:我应该提到我正在将mongo与.NET驱动程序配合使用,因此我可以使用LINQ。

Have you looked at Mongo aggregation ? 您是否看过Mongo聚合? If you want to return the 1000 most recent summaries you could go with an $unwind followed by a $replaceRoot operation, here's the shell query I tried : 如果您想返回1000个最新的摘要,可以使用$ unwind和$ replaceRoot操作,这是我尝试过的shell查询:

db.getCollection('test').aggregate([
{$match : {your timestamp match query here}},
{$sort : {"timestamp": -1}},
{$unwind : "$summaries"},
{$limit : 1000},
{$replaceRoot: {newRoot: "$summaries"}}
])

The match operation at the beginning of your aggregation pipeline is important as indexes are only used at the first step. 聚合管道开始处的match操作非常重要,因为仅在第一步使用索引。 If you unwind your whole collection your performance might drop drastically. 如果您放松整个收藏,您的表现可能会急剧下降。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM