Lets say a document is :
{
a: 1,
b: 1,
c: 2,
....
z: 2
}
How can I count the number of keys in such document?
Thank you
Sergio is right, you have to do it outside of mongo.
You can do something like this:
var count = 0;
for(k in obj) {count++;}
print(count);
If You are work with Documents like the mongoose.Document, You can try to count all keys inside the doc after transform in a object, 'cause, before it, the doc just have commom properties:
Object.keys(document); // returns [ '$__', 'isNew', 'errors', '_doc', '$locals' ]
Object.keys(document).length; // returns ALWAYS 5
So, try cast to an object, after pass it to Object.keys
console.dir(
Object.keys(document.toObject()) // Returns ['prop1', 'prop2', 'prop3']
);
And to show the keys count
console.log(
Object.keys(document.toObject().length)
); // Returns 3
And Be Happy!!!
const MongoClient = new require("mongodb").MongoClient(
"mongodb://localhost:27017",
{
useNewUrlParser: true,
useUnifiedTopology: true
}
);
(async () => {
const connection = await MongoClient.connect();
const dbStuff = await connection
.db("db")
.collection("weedmaps.com/brands")
.find({})
.toArray(); // <- Chuck all it into an Array
for (let thing of dbStuff) {
console.log(Object.keys(thing).length);
}
return await connection.close();
})();
There's no built-in command for that. Fetch this document and count the keys yourself.
If you are in Mongo console, you can write javascript to do that.
doc = db.coll.findOne({}); nKeys =0; for( k in doc){nKeys ++;} print(nKeys);
This will still be considered "outside the mongo" though.
In Mongo (as in most NoSQL solutions) it's usually a good idea to pre-calculate such values if you want to do queries on them later (e.g. "where the number of different keys > 12") so maybe you should consider adding a new field "keyCount" which you increment every time a new key is added.