0

I need to pull the latest date from a collection on mongo db and set it in a shell script.

LASTDOCDATE=mongo mongo.com:27017/tracking -u user -p pw   --authenticationDatabase authdb  --eval 'db.TRACKING_DATA.find({},{datecreated :1}).limit(1).sort({datecreated:-1}).map(function (doc){ return doc.datecreated; })'

echo $LASTDOCDATE

This to be set but when run through the terminal produces:

connecting to: mongo.com:27017/tracking
Mon Jul 27 2015 16:28:08 GMT-0700 (PDT)

have can I pull just the date attribute to be set in a shell script as a variable

Blakes Seven
  • 49,422
  • 14
  • 129
  • 135
Will
  • 8,246
  • 16
  • 60
  • 92
  • 1
    I think you're just missing the [command substitution](http://www.gnu.org/software/bash/manual/bashref.html#Command-Substitution) syntax: `last_doc_date=$(mongo ...)` -- Also, [don't use ALL_CAPS_VARS](http://stackoverflow.com/questions/28310594/ls-not-found-after-running-read-path) – glenn jackman Jul 28 '15 at 00:47

1 Answers1

1

Wrap your call with the printjson() method of the shell in order to get an output string:

LASTDOCDATE=mongo mongo.com:27017/tracking -u user -p pw  \\
--authenticationDatabase authdb \\
--eval 'printjson(db.TRACKING_DATA.find({},{datecreated :1}).limit(1).sort({datecreated:-1}).map(function (doc){ return doc.datecreated; }))'

Or just print, while referencing the single element:

LASTDOCDATE=mongo mongo.com:27017/tracking -u user -p pw  \\
--authenticationDatabase authdb \\
--eval 'print(db.TRACKING_DATA.find({},{datecreated :1}).limit(1).sort({datecreated:-1}).toArray()[0].datecreated'

Notating the single array element, and then the property:

.find({},{datecreated :1}).limit(1).sort({datecreated:-1}).toArray()[0].datecreated'

Or findOne() like this with $orderby:

.findOne(
    { "query": {}, "$orderby": { "datecreated": 1 }},
    { "_id": 0, "datecreated": 1 }
).datecreated

So .print() or .printjson() depending on the output format you want. Or even .valueOf() on the "datecreated" to just get the timestamp value rather than the string.

Blakes Seven
  • 49,422
  • 14
  • 129
  • 135