prashantas
prashantas

Reputation: 455

variable collection name in mongodb shell using javascript

Using the mongo shell which is javascript:

db.collection.insert() 

Can I allow the collections name to be dynamic so as to work with several collections?

Upvotes: 4

Views: 10431

Answers (4)

Kai
Kai

Reputation: 3693

here is my idea for this issue, check if it helps:

function insertIntoColumn(colName){
   if(!colName) {
       return;
   }
   return db[colName].insert();
}

Upvotes: 5

Satish
Satish

Reputation: 746

From the mongo shell:

You can create variable using var for collection name

var colName = "mytest"

and then execute all the operations on collections as below:

db[colName].find()

db[colName].rename("newName")

etc. This will help you keep your collection name dynamic and can even update it keeping your commands same.

Hope this helps!

Upvotes: 11

BrentR
BrentR

Reputation: 928

// This seems to work too.

var collectionNames = ["collection1", "collection2"];
collectionNames.forEach(function(collectionName) {
    var collection = db.getCollection(collectionName);

    collection.find();
});

Upvotes: 2

Neil Lunn
Neil Lunn

Reputation: 151132

If you are just talking about the mongo shell:

var col = db.collection;
col.find()

And all other commands are quite valid. The same goes for the database:

var odb = db.getSiblingDB("other")

And now odb works on the "other" database.

odb.othercollection

Would be working with "othercollection" in the "other" database, while db was still the current one.

It's all just JavaScript, so anything for an "object" is valid.

Upvotes: 4

Related Questions