Search code examples
node.jsmongodbmongo-shell

How do I print/use a specific value of a key in mongo shell script?


I'm running the following from the shell;

const records = db.issues.find().limit(1);

print('Record:', records);
print('ID:', records.id);

It returns one record;

Record: [
  {
    _id: ObjectId("63f94e684902f564f7d418ca"),
    id: 1,
    status: 'New',
    owner: 'Ravan',
    effort: 5,
    created: ISODate("2019-01-15T00:00:00.000Z"),
    due: null,
    title: 'Error in console when clicking Add',
    description: 'Steps to recreate the problem:\n'
  }
]

So I thought the last line would produce;

ID: 1

It just produces ID:, without an error, what am I missing?

The next question would then be how do I iterate thru the cursor if multiple records are returned?

Cheers C.


Solution

  • find() method returns a cursor that can be iterated over to retrieve each document. In your example, records is a cursor that returns an array with one document. To print/use a specific value of a key in the document, you need to access that value using dot notation or bracket notation :

    print('ID:', records[0].id);
    

    Iterate through the cursor, you can use a forEach() (if multiple records are returned) :

    const records = db.issues.find();
    
    records.forEach(function(record) {
      print('ID:', record.id);
    });