MongoDB gets the total number of filtered messages

problem description

I want to get the total number of entries matching the query condition, total. How can I get it better?
what I"m doing now is to set another layer of query on the outside, which I don"t think is good.

db.collection("netdatas").find(query).count().then(total=>{
    db.collection("netdatas").find(query).sort(sort).skip((page - 1)*num).limit(num).toArray().then(docs=>{
    ws.send(JSON.stringify({
        cmd:"query_netdatas",
        data:{
            num,
            page,
            total,
            records:docs
        }
    }))
})
})

I can use aggregation after taking a look, but I didn"t get it ~

how can I easily get the total number of total messages filtered by query?

Apr.11,2022

from a database perspective, these are two completely different things. The reason is also simple: if you only need the first N items, the database can stop when you find out what's in front of you. But to find total, the database needs to find all the eligible data, which is obviously much heavier than the former. But the latter is just counting, while the former is to find out the real documents. In short, it is impossible to get a completely different execution plan at the same time.
if you want to talk about improvement, it is recommended to take a look at Promise. Two queries can be executed asynchronously at the same time. You don't have to execute one before the other.
finally, from a design point of view, it is often inappropriate to use this method in big data scenarios. The efficiency of count and skip/limit are not good when there is a large amount of data, and this design is not recommended.

  • Mongoose conditional query?

    problem description if you want to get a piece of data required by composition in the course field, the data returned after using find contains excess data, and the result is not ideal. In order to achieve this goal, how to write code, it seems that...

    Apr.26,2021
Menu