簡體   English   中英

如何使用MongoDB和Node.js按值數組計數

[英]How to get count by array of values using MongoDB and Node.js

我需要使用MongoDB和Node.js獲取文檔總數。 我在下面解釋我的代碼和文檔。

var finalOut=[
    {
        "location": "NEW DELHI",
        "nos_of_fos": 15,
        "login_id": [
            "9619300317",
            "9619300343",
            "9619300338",
            "9619300351",
            "9619300322",
            "9619300316",
            "9619300323",
            "9619300328",
            "9619300341",
            "9619300309",
            "9619300310",
            "9619300329",
            "9619300353",
            "9619300356",
            "NORTH@oditeksolutions.com"
        ],

    },
    {
        "location": "North West Delhi",
        "nos_of_fos": 6,
        "login_id": [
            "9619300355"
        ],

    }
]

以上是我的意見。 我在下面解釋我的代碼。

finalOut.forEach(function(listItem, index){
                    Feedback.collection.aggregate([
                        {
                            $match: {
                                login_id: {
                                    $in: listItem['login_id']
                                }
                            }
                        },

                    ])
                    .toArray((cerr,cdocs)=>{
                        console.log(cdocs);
                    })
                    finalOut[index]['total_remarks']=cdocs;
                })

在這里,我需要feedback文檔中存在的所有login_id數組值的總數。

您不能將forEach用於異步操作:

在這里,我將使用異步庫,但您可以使用任何喜歡的庫。

async.forEachOf(finalOut, (listItem, index, callback) => {
    Feedback.collection.aggregate([
        {
            $match: {
                login_id: {
                    $in: listItem['login_id']
                }
            }
        },
        {
            $count: ‘theCount’
        }
    ])
    .toArray((cerr,cdocs)=> {
        finalOut[index]['total_remarks']=cdocs.theCount;
        callback();
    })
}, err => {
    // here you can access the filled `finalOut` object
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM