How to view document fields in mongo shell?

前端 未结 5 741
一个人的身影
一个人的身影 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:24

    Even easier:

    Object.keys(db.messages.findOne())
    
    0 讨论(0)
  • 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]);
        }
    });
    
    // ------------
    
    0 讨论(0)
  • 2020-12-25 14:33
    var task = db.task.find().next()
    for (let key in task){print(key)}
    

    enter image description here

    0 讨论(0)
  • 2020-12-25 14:37

    A for ... in loop should do the trick:

    > var message = db.messages.findOne();
    > for (var key in message) {
    ... print(key);
    ... }
    
    0 讨论(0)
  • 2020-12-25 14:47

    To get a list of all fields used in a collection in MongoDB, this is the way I found most straightforward (your mileage may vary :) ):

    Create a .js file with the content:

    use yourdbname
    mr = db.runCommand({
      "mapreduce" : "collectionName",
      "map" : function() {
        for (var key in this) { emit(key, null); }
      },
      "reduce" : function(key, stuff) { return null; },
      "out": "collectionName" + "_keys"
    })
    db[mr.result].distinct("_id")
    

    I found out how to do this here (GeoffTech blog)

    I ran it from the shell to print the output in the console

    mongo < nameOfYourFile.js 
    

    or dump the output in a text file:

    mongo < nameOfYourFile.js > outputDir\nameOfYourOutputFile.txt
    

    I'm totally new to MongoDb so I hope it does indeed get all fields regardless of use throughout the documents!

    (I'm using MongoDb on windows 10, so my console may differ from yours)

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