MongoDB的 - 通过

问题描述:

选择收藏和索引我正在在NoSQL的第一步骤,有以下问题:MongoDB的 - 通过

说我们有在名为“EmployeeNumber”领域的数据库中的几个集合。

我该如何编写一个脚本来选择所有具有此字段的集合名称以及所有使用此列的索引名称?

+2

MongoDB中没有列。 Colums是SQL的一个属性。 Mongodb存储具有不同模式的文档。 – user2647513

+0

对不起,我的意思是田野。修正了帖子。 – user306080

+1

迭代所有集合并检查每个集合以查找所需的集合。 Doc这里:https://docs.mongodb.com/manual/reference/method/ – JohnnyHK

简答:你不能。

集合没有Schema,因此您可以检查所有集合以查看它们是否包含属性为EmployeeNumber的记录,但那样会很糟糕。

如果你想它会看起来像:

function findCollectionsWithEmployeeNumber(cb){ 
    var collectionsWithEmployeeNumber = []; 
    var collectionsToCheck = {}; 
    db.collectionNames(function(err, collections){ 
     collections.forEach(function(c){collectionsToCheck[c]=false}); 
     if(err) { 
      throw err; 
     } 
     collections.forEach(function(collection){ 
      db[collection].findOne({EmployeeNumber : {$exists :true}}, function(err, res){ 
       if(res) { 
        collectionsWithEmployeeNumber.push(collection); 
       } 
       collectionsToCheck[collection] = true; 
       var allChecked = collectionsToCheck.reduce(function(previous, current){return previous && current}, true) 
       if(allChecked) { 
        cb(collectionsWithEmployeeNumber); 
       } 
      }) 
     }); 
    }); 
} 
+1

有趣的答案:1.你不能。好吧,你可以但它会很糟糕。好的,让我为你写。 :-) – JohnnyHK