How to view document fields in mongo shell?

前端 未结 5 785
一个人的身影
一个人的身影 2020-12-25 14:08

Is there a way to figure out the fields/keys in a document while in mongo\'s shell? As an example, let\'s say we have a document like (pseudocode):

{
    \"m         


        
5条回答
  •  盖世英雄少女心
    2020-12-25 14:28

    Other answers are correct.

    However, as I am completely new, I didn't understand where & how the above commands need to be executed.

    Below helped, from my github.
    On Windows: Run this code in a command prompt (cmd).
    On Mac or Linux: Run this code in a terminal window.

    // ------------
    // start mongo client
    mongo
    
    // ------------
    
    // list all databases
    show dbs
    // NOTE: assume one of the databases is myNewDatabase
    
    // use the 'myNewDatabase' database
    use myNewDatabase
    
    // ------------
    
    // show all collections of 'myNewDatabase' database
    show collections
    // NOTE: assume one of the collections is 'myCollection'
    
    // show all documents of 'myCollection' collection
    db.myCollection.find()
    
    // ------------
    
    // field keys
    Object.keys(db.myCollection.findOne());
    
    // values
    db.myCollection.find().forEach(function(doc) {
        for (field in doc) {
            print(doc[field]);
        }
    });
    
    // ------------
    

提交回复
热议问题