我的文档如下所示:
{
"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.
});
});
});
答案 0 :(得分:1)
您可以使用聚合框架来执行此操作:
db.col.aggregate([
{
$project: {
numberOfKeys: {
$let: {
vars: { array: { $objectToArray: "$$ROOT" } },
in: { $add: [{ $size: "$$array" }, -1] }
}
}
}
}
])
对于每个文档,我们都会进行投影,返回_id和一些键。二手经营者: