alfheimrShiven
alfheimrShiven

Reputation: 55

How to count the number of key value pairs in a mongodb document using node.js?

My document looks like the following:

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

I need to know the number of elements inside the document. For example, here there are 4 key/value pairs. I'm retrieving the doc on my nodejs server like this

    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.    
        });
    });
});

Upvotes: 0

Views: 148

Answers (1)

mickl
mickl

Reputation: 49985

You can use aggregation framework to do that:

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

For each document we're doing a projection which will return _id and a number of keys. Used operators:

  • $let to define temporary variable
  • temporary variable array contains all the keys and values inside entire document ($$ROOT is a special variable representing whole doc), to get those keys and values we're using $objectToArray
  • $size measures the size of an array (length), we also need to subtract 1 representing _id if you don't want to include it in a result

Upvotes: 1

Related Questions