How do I describe a collection in Mongo?

前端 未结 12 597
终归单人心
终归单人心 2021-01-31 02:32

So this is Day 3 of learning Mongo Db. I\'m coming from the MySql universe...

A lot of times when I need to write a query for a MySql table I\'m unfamiliar with, I woul

相关标签:
12条回答
  • 2021-01-31 02:43

    While factually correct, you're all making this too complex. I think the OP just wants to know what his/her data looks like. If that's the case, you can just

    db.collectionName.findOne()
    

    This will show one document (aka. record) in the database in a pretty format.

    0 讨论(0)
  • 2021-01-31 02:46

    If you are using NodeJS and want to get the all the field names using the API request, this code works for me-

    let arrayResult = [];
    
    db.findOne().exec(function (err, docs)){
     if(err)
      //show error
    
      const JSONobj = JSON.parse(JSON.stringify(docs));
         for(let key in JSONobj) {
           arrayResult.push(key);
         }
      return callback(null, arrayResult);
    }
    

    The arrayResult will give you entire field/ column names

    Output-

    [
     "_id",
     "emp_id",
     "emp_type",
     "emp_status",
     "emp_payment"
    ]
    

    Hope this works for you!

    0 讨论(0)
  • 2021-01-31 02:48

    You can use a UI tool mongo compass for mongoDb. This shows all the fields in that collection and also shows the variation of data in it.

    0 讨论(0)
  • 2021-01-31 02:51

    Type the below query in editor / mongoshell

    var col_list= db.emp.findOne();
    for (var col in col_list) { print (col) ; }
    

    output will give you name of columns in collection :

    _id
    name
    salary
    
    0 讨论(0)
  • 2021-01-31 02:54

    There is no good answer here. Because there is no schema, you can't 'describe' the collection. In many (most?) MongoDb applications, however, the schema is defined by the structure of the object hierarchy used in the writing application (java or c# or whatever), so you may be able to reflect over the object library to get that information. Otherwise there is a bit of trial and error.

    0 讨论(0)
  • 2021-01-31 02:57
    print('\n--->', Object.getOwnPropertyNames(db.users.findOne())
      .toString()
      .replace(/,/g, '\n---> ') + '\n');
    

    ---> _id
    ---> firstName
    ---> lastName
    ---> email
    ---> password
    ---> terms
    ---> confirmed
    ---> userAgent
    ---> createdAt
    
    0 讨论(0)
提交回复
热议问题