Is it possible to generate dynamically-named Mongo

2019-01-20 18:34发布

问题:

Normally, MongoDB Collections are defined like this:

DuckbilledPlatypi = new Mongo.Collection("duckbilledplatypi"); 

I want to, though, dynamically generate Collections based on user input. For example, I might want it to be:

RupertPupkin20151212_20151218 = new Mongo.Collection("rupertPupkin20151212_20151218"); 

It would be easy enough to build up the Collection name:

var dynCollName = username + begindate +'_'+ enddate;

...and then pass "dynCollName") to Mongo.Collection:

 = new Mongo.Collection(dynCollName); 

...but what about the Collection instance name - how can that be dynamically generated? I would need something like:

"RupertPupkin20151212_20151218".ToRawName() = new Mongo.Collection(dynCollName);

-or:

"RupertPupkin20151212_20151218".Unstringify() = new Mongo.Collection(dynCollName);

...but AFAIK, there's no such thing...

回答1:

On a single client instance, yes, and you could dynamically reference it. However in the general case (using it to sync data between the server and all connected clients), no.

I address this point in the Dynamically created collections section of common mistakes in a little detail, but the fundamental problem is that it would be highly complex to get all connected clients to agree on a dynamically generated set of collections.

It's much more likely that a finite set of collections where some have a flexible schema, is actually what you want. As Andrew Mao points out in the answer to this related question, partitioner is another tool available to help address some cases which give rise to this question.