The name of a collection variable in mongodb shell using javascript

Using mongo shell, which is javascript:

db.collection.insert() 

Can I allow the collection name to be dynamic in order to work with multiple collections?

+4
source share
4 answers

If you just talk about the mongo shell:

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

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

var odb = db.getSiblingDB("other")

And now it odbworks with a "different" database.

odb.othercollection

Will work with "othercollection" in a "different" database, while it dbis still current.

All this is just JavaScript, so everything for the “object” is valid.

+4
source

:

, var

var colName = "mytest"

, :

db[colName].find()

db[colName].rename("newName")

... , .

, !

+8

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

function insertIntoColumn(colName){
   if(!colName) {
       return;
   }
   return db[colName].insert();
}
+5
source
// This seems to work too.

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

    collection.find();
});
+2
source

Source: https://habr.com/ru/post/1532421/


All Articles