'mongodb': how to retrieve values from an object in shell script

I use a shell script to query MongoDB:

#!/bin/bash

mongoexport -d db -c collection -f Id

I have:

  { _id: ObjectId("641e883ec0a3fde195b59019"), Id: '12027311490' },
  { _id: ObjectId("641e8845c0a3fde195b5901b"), Id: '15400490185' },
  { _id: ObjectId("641e884dc0a3fde195b5901d"), Id: '775662862079' },
  { _id: ObjectId("641e8852c0a3fde195b5901f"), Id: '68236165355' },
  { _id: ObjectId("641e885ac0a3fde195b59021"), Id: '74174554856' },
  { _id: ObjectId("641e8861c0a3fde195b59023"), Id: '525514528629' },
  { _id: ObjectId("641e8868c0a3fde195b59025"), Id: '85838105070' },
  [...]

How can I parse properly the id digits without mongodb id’s and without all the mess around?

Expected output:

12027311490
15400490185
775662862079
68236165355
74174554856
525514528629
85838105070

I know I can use ‘grep’ or ‘sed’, but I search a proper way.

>Solution :

Use mongoexport, with output format ‘csv’, selecting just the field you want:

mongoexport -d "mydb" -c "collection" -f Id --type csv --noHeaderLine --quiet

Leave a Reply