Reputation: 55
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
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:
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 $objectToArrayUpvotes: 1