在单个mongodb查询中查找并计数 [英] find and count in single mongodb query

查看:67
本文介绍了在单个mongodb查询中查找并计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的文档看起来像这样.

My documents looks like this.

{
"_id" : ObjectId("572c4bffd073dd581edae045"),
"name" : "What's New in PHP 7",
"description" : "PHP 7 is the first new major version number of PHP since 2004. This course shows what's new, and what's changed.",
"difficulty_level" : "Beginner",
"type" : "Normal",
"tagged_skills" : [ 
    {
        "_id" : "5714e894e09a0f7d804b2254",
        "name" : "PHP"
    }
],
"created_at" : 1462520831.649,
"updated_at" : 1468233074.243    }

是否有可能在一个查询中获得最近的5个文档和总数. 我为此要求使用了两个查询.

Is it possible to get recent 5 documents and total count in a single query. I am using two queries for this requirement as given below.

db.course.find().sort({created_at:-1}).limit(5)
db.course.count()

推荐答案

对于聚合框架而言,这是一项完美的工作.

This is a perfect job for the aggregation framework.

db.course.aggregate(
    [
        { "$sort": { "created_at": -1 }},
        { "$group": {
            "_id": null, 
            "docs": { "$push": "$$ROOT" }, 
            "count": { "$sum": 1 }
        }},
        { "$project": { "_id": 0, "count": 1, "docs": { "$slice": [ "$docs", 5 ] } }}
    ]
)


如果您的MongoDB服务器不支持 $slice 那么您需要使用丑陋而低效的方法.


If your MongoDB server doesn't support $slice then you need to use the ugly and inefficient approach.

db.course.aggregate(
    [
        { "$sort": { "created_at": -1 }},
        { "$group": {
            "_id": null, 
            "docs": { "$push": "$$ROOT" }, 
            "count": { "$sum": 1 }
        }},
        { "$unwind": "$docs" },
        { "$limit": 5 }
    ]
)

这篇关于在单个mongodb查询中查找并计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆