Mongo-获取中介文件的数量

发布于 2025-02-06 17:13:30 字数 1050 浏览 1 评论 0原文

目前,我有一个查询:

const result = await getInstances();

为我提供了一系列文档:

[{name: "first", age: 13},
{name: "second", age: 21},
{name: "third", age: 11},
{name: "fourth", age: 14}
...]  

查询是这样的:

...
return Instances.aggregate
         .match({//condition})
         .skip(skipValue).limit(pageSize) // pagination done here

我想要一个查询,以附加总数。分页之前的文档,但返回分页的数据,例如:

...
return Instances.aggregate
         .match({//condition}) ## I WANT THE COUNT OF THIS STEP TO BE APPENDED
         .<SOME_PIPELINE_HERE>
         .skip(skipValue).limit(pageSize) // pagination done here
  

将返回类似的内容:

{
  data: [{name: "first", age: 12}....<ALL_PAGINATED_DATA>],
  totalCount: 54  #count of data before pagination
}

我尝试过的和不起作用的内容:

Instances.aggregate()
  .match({//CONDITION})
  .addFields({count: {$size: _id}})
  .skip(value).limit(value)

看来,它可以通过并为每个文档而不是整个文档进行计算

currently I have a query:

const result = await getInstances();

that provides me an array of document:

[{name: "first", age: 13},
{name: "second", age: 21},
{name: "third", age: 11},
{name: "fourth", age: 14}
...]  

The query goes something like this:

...
return Instances.aggregate
         .match({//condition})
         .skip(skipValue).limit(pageSize) // pagination done here

I want a query that appends a count for the total no. of documents before the pagination, but returns the paginated data, e.g:

...
return Instances.aggregate
         .match({//condition}) ## I WANT THE COUNT OF THIS STEP TO BE APPENDED
         .<SOME_PIPELINE_HERE>
         .skip(skipValue).limit(pageSize) // pagination done here
  

would return something like:

{
  data: [{name: "first", age: 12}....<ALL_PAGINATED_DATA>],
  totalCount: 54  #count of data before pagination
}

What I tried and didn't work:

Instances.aggregate()
  .match({//CONDITION})
  .addFields({count: {$size: _id}})
  .skip(value).limit(value)

It seems it goes through and calculates this for each document instead of the whole

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

成熟稳重的好男人 2025-02-13 17:13:30

一种选项是使用$ facet以“分叉”中间的查询,因此可以在不同的管道上使用相同的数据。例如:

db.collection.aggregate([
  {$match: {a: {$in: [7, 8, 9]}}},
  {
    $facet: {
      total: [{$group: {_id: null, count: {$sum: 1}}}],
      data: [{$skip: 1}]
    }
  },
  {$project: {data: 1, total: {$first: "$total.count"}}}
])

请参阅游乐场示例

One option is to use $facet in order to "fork" the query in the middle, so the same data can be used on different pipelines. For example:

db.collection.aggregate([
  {$match: {a: {$in: [7, 8, 9]}}},
  {
    $facet: {
      total: [{$group: {_id: null, count: {$sum: 1}}}],
      data: [{$skip: 1}]
    }
  },
  {$project: {data: 1, total: {$first: "$total.count"}}}
])

See how it works on the playground example

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文