如何使用node.js计算mongodb文档中键值对的数量?

时间:2018-01-28 10:30:33

标签: node.js mongodb

我的文档如下所示:

{
    "Erow1": "funnnyyyy hahaha",
    "Erow2": "Prefer a public role",
    "Erow3": "Can sometimes be easily distracted",
    "Erow4": "I'm awesome"
}

我需要知道文档中的元素数量。例如,这里有4个键/值对。 我正在我的nodejs服务器上检索这个文档

    app.get("/editMBTI", function editMBTIFunc(req, res)
{ 
    MongoClient.connect(url, function (err, client) {
        assert.equal(null, err);
        console.log("Connected Successfully to the Database server");
        const db = client.db(dbName);
        //getting the whole collection of MBTI sets
        var cursor= db.collection("mbti_testcontent").find();
        cursor.toArray(function (err, doc) {
            assert.equal(err, null);
            console.log(doc[0]);
            // get the count of the key-value pairs present in doc[0] here.    
        });
    });
});

1 个答案:

答案 0 :(得分:1)

您可以使用聚合框架来执行此操作:

db.col.aggregate([
    { 
        $project: {
            numberOfKeys: {
                $let: { 
                    vars: { array: { $objectToArray: "$$ROOT" } },
                    in: { $add: [{ $size: "$$array" }, -1] }
                }
            }
        }
    }
])

对于每个文档,我们都会进行投影,返回_id和一些键。二手经营者:

  • here定义临时变量
  • 临时变量array包含整个文档中的所有键和值($$ROOT是表示整个文档的特殊变量),以获取我们使用{{3}的那些键和值}
  • $let衡量数组的大小(长度),如果您不希望将结果包含在结果中,我们还需要减去1代表_id