32

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):

{
    "message": "Hello, world",
    "from": "hal",
    "field": 123
}

I'd like to run a command in the shell that returns the list of fields/keys in that document. For instance, something like this:

> var message = db.messages.findOne()
> message.keys()
... prints out "message, from, field"
SecretAgentMan
  • 2,856
  • 7
  • 21
  • 41
Rob
  • 7,377
  • 7
  • 36
  • 38

6 Answers6

70

Even easier:

Object.keys(db.messages.findOne())
Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
Will Fitzgerald
  • 1,372
  • 10
  • 14
  • 4
    In the hope that Google indexes comments... I found this while looking for something in Mongo like SQL's "DESCRIBE". – danielpcox Mar 16 '15 at 21:24
  • 1
    This (and the other answers that use `findOne`) will only work correctly if every document in the database contains a value for every possible field. Otherwise you will only get the keys that were contained in whatever document you happened to get from `findOne`. – Jason Kohles Feb 12 '21 at 20:38
11

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

> var message = db.messages.findOne();
> for (var key in message) {
... print(key);
... }
Shane Andrade
  • 2,655
  • 17
  • 20
10

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]);
    }
});

// ------------
Félix Paradis
  • 5,165
  • 6
  • 40
  • 49
Manohar Reddy Poreddy
  • 25,399
  • 9
  • 157
  • 140
2

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)

zanther
  • 537
  • 1
  • 4
  • 15
  • Should probably mention that you need to also follow this with `db.collectionName_keys.drop()` to get rid of the collection that it stored the results in. – Jason Kohles Feb 12 '21 at 20:37
2

You can do this in a way that gets all the fields even if not every document in the collection has some of them, and without creating a collection:

    return db.collectionName.aggregate( [
      { $project : { x : { $objectToArray : "$$ROOT" } } },
      { $unwind : "$x" },
      { $group : { _id : null, keys : { $addToSet : "$x.k" } } },
    ] ).toArray()[0].keys.sort();

This is also a handy thing to add to the Mongo shell, which you can do by including it your .mongorc.js file in your home directory:

Object.assign( DBCollection.prototype, {
  getAllFieldNames() {
    return db[ this._shortName ].aggregate( [
      { $project : { x : { $objectToArray : "$$ROOT" } } },
      { $unwind : "$x" },
      { $group : { _id : null, keys : { $addToSet : "$x.k" } } },
    ] ).toArray()[0].keys.sort();
  },
} );

Then you can just do db.myCollection.getAllFieldNames() when using the shell..

Jason Kohles
  • 597
  • 5
  • 12
0
var task = db.task.find().next()
for (let key in task){print(key)}

enter image description here

4b0
  • 21,981
  • 30
  • 95
  • 142
符瑞阳
  • 111
  • 1
  • 3