MongoDB: how to count number of keys in a document?

后端 未结 7 1511
一向
一向 2020-12-11 14:46

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

7条回答
  •  爱一瞬间的悲伤
    2020-12-11 15:01

    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!!!

提交回复
热议问题