find and count in single mongodb query

狂风中的少年 提交于 2019-12-08 12:18:42

问题


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    }

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()

回答1:


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 ] } }}
    ]
)

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 }
    ]
)



回答2:


@styvane I tested in person, this query is even less efficient than twice queries.

// get count 
db.course.aggregate([{$match:{}}, {$count: "count"}]);
    // get docs
db.course.aggregate(
       [
            {$match:{}},
            { "$sort": { "created_at": -1 }},
            {"$skip": offset},
            {"$limit": limit}
        ]
)



回答3:


No, there is no other way. Two queries - one for count - one with limit.



来源:https://stackoverflow.com/questions/38765389/find-and-count-in-single-mongodb-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!