SteveO7
SteveO7

Reputation: 2460

Mongodb aggregation $out dynamic collection name

I am looking for a way to incorporate the date into the collection name that is created in the $out stage of a Mongodb aggregation pipeline.
Something like this (but it doesnt work)

db.sales.aggregate([{$project: {account_number:1}},    
 {$out: "new_collection" + Date()}]);

This returns the following error;

The specification of Stage 2 contains invalid JSON: Unexpected character '+' at line 1, col 18

Anyone know how I could do this?

Upvotes: 0

Views: 580

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311835

Date() returns a long string version of the date which can contain characters that can't be used in collection names. For example:

'Wed Dec 23 2015 22:47:53 GMT-0600 (Central Standard Time)'

So you probably want to use something like Date.now() instead, which returns a ms count like 1450932419617 which will work in a collection name.

{$out: "new_collection" + Date.now()}

giving you a valid collection name like 'new_collection1450932419617'.

Upvotes: 2

Related Questions