4

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?

4 Answers 4

11

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!

Sign up to request clarification or add additional context in comments.

Comments

5

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

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

2 Comments

why not just db[colName].insert(); ?
thanks for notice it. I'll update. Such a dump code, maybe I did some magic then remove it haha.
4

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.

Comments

2
// This seems to work too.

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

    collection.find();
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.