i have a set of 300000 documents in mongodb

my function takes about 40 secounds to display results, how to make it faster?

async function getAllWebsite(req, res) {

    var nameWebsites = await Article.distinct("website.name");
    var idWebsites = await Article.distinct("website.id");
    var numberArticle = [];
    var result = [];

    for(var i = 0; i < nameWebsites.length; i++) {
        await Article.aggregate([
            { $match: {"website.id": idWebsites[i]}},
            { $count: "count"}        
        ], function(err, result){
            numberArticle.push(result);
        });
    }

    for(var i = 0; i < nameWebsites.length; i++) {
        result.push({"id":idWebsites[i], "name":nameWebsites[i], "number_article": numberArticle[i][0].count});
    }

    var count = result.length;
    res.json({
        data: result,
        total: count,
    });   
}

this is my solution but it only display "loading " not my result, i think the reason is my function was too slow

componentDidMount() {
        fetch("http://localhost:3030/api/articles/website")
        .then(res => res.json())
        .then(datas => this.setState({ results: datas.data}))
    }

    render() {
        const { results, isLoading } = this.state;

        return <div className="main-content">   
        { !isLoading ? (
            results.map((website) => {
                return(
                    <div>
                        <p>Id: {website.id}</p>
                        <p>Name: {website.name}</p>
                    </div>
              )
            })
            ):(<h3>Loading...</h3>)
        }
        </div>;
    }

0 Answers