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

后端 未结 7 1422
一向
一向 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 14:57

    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);
    
    0 讨论(0)
  • 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!!!

    0 讨论(0)
  • 2020-12-11 15:05
    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();
    })();
    
    0 讨论(0)
  • 2020-12-11 15:15

    There's no built-in command for that. Fetch this document and count the keys yourself.

    0 讨论(0)
  • 2020-12-11 15:15

    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.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题