簡體   English   中英

使用javascript在mongodb shell中的變量集合名稱

[英]variable collection name in mongodb shell using javascript

使用javascript的mongo shell:

db.collection.insert() 

我可以允許集合名稱是動態的,以便使用多個集合嗎?

來自mongo shell:

您可以使用var為集合名稱創建變量

var colName = "mytest"

然后執行對集合的所有操作,如下所示:

db[colName].find()

db[colName].rename("newName")

這將幫助您保持您的集合名稱動態,甚至可以更新它,保持命令相同。

希望這可以幫助!

這是我對這個問題的想法,檢查它是否有幫助:

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

如果你只是在談論mongo shell:

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

所有其他命令都非常有效。 數據庫也是如此:

var odb = db.getSiblingDB("other")

現在odb適用於“其他”數據庫。

odb.othercollection

將在“其他”數據庫中使用“othercollection”,而db仍然是當前的數據庫。

它只是JavaScript,因此“對象”的任何內容都是有效的。

// This seems to work too.

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

    collection.find();
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM