有没有办法在MongoDB中的一个查询中获取文档和文档计数?

发布于 2025-02-04 10:31:36 字数 207 浏览 2 评论 0原文

result = db.collection.find({})

这将返回我们的收集文件。

count = db.collection.count_documents({})

这将返回我们收集中的文件计数。

我想在一个查询中获得文档和文档计数。

有解决方案吗?

result = db.collection.find({})

This will return us documents of collection.

count = db.collection.count_documents({})

This will return us count of documents in collection.

I want to get both of documents and count of documents in one query.

Any solutions?

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

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

发布评论

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

评论(1

℉絮湮 2025-02-11 10:31:36

一种方法是使用汇总,

db.collection.aggregate([
    // you can write you query inside $match
    { $match: {} },
    { 
        $facet: {
            // getting total records
            metaData: [{
                $group: {
                    _id: null,
                    totalCount: { $sum: 1 }
                }
            }],
            records: []
        } 
    }
]);

另一种做法是使用第三方模块,例如mongoose-paginate-v2,它将为您提供所有数据,并提供简单的查找查询。

One way of doing it is to use aggregation,

db.collection.aggregate([
    // you can write you query inside $match
    { $match: {} },
    { 
        $facet: {
            // getting total records
            metaData: [{
                $group: {
                    _id: null,
                    totalCount: { $sum: 1 }
                }
            }],
            records: []
        } 
    }
]);

Another way of doing it is to use third party module like mongoose-paginate-v2, it will provide you all the data with your simple find query.

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