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

后端 未结 7 1533
一向
一向 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:20

    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.

提交回复
热议问题