【问题标题】:mongodb native driver get collection names without database namemongodb本机驱动程序获取没有数据库名称的集合名称
【发布时间】:2014-07-05 16:24:53
【问题描述】:

如何从 nodeJS 的 mongodb 本机驱动程序中获取没有数据库名称的集合名称?

db.collectionNames(function(err, collections) {
      if (err) {
        log.error(err);
      } else {
        log.info(collections);
      }
    });

此代码返回如下内容:

databaseName.collection1、databaseName.collection2、databaseName.collection3

但我想得到名字:collection1, collection2, collection3

【问题讨论】:

    标签: javascript node.js mongodb node-mongodb-native


    【解决方案1】:

    使用 MongoDB 2.0.0 驱动程序及更高版本,您将need to use listCollections(),如

    db.listCollections().toArray(function(err, collections){
        //collections = [{"name": "coll1"}, {"name": "coll2"}]
    });
    

    【讨论】:

      【解决方案2】:

      响应的确切结构是一个带有数组中“name”键的子文档:

      [
        { name: 'test.cursors' },
        { name: 'test.episodes' },
        { name: 'test.zips' },
        { name: 'test.scripts' }
      ]
      

      所以只需使用map 和正则表达式replace:

      db.collectionNames(function(err, collections) {
      
        console.log(
          collections.map(function(x) {
            return x.name.replace(/^([^.]*)./,"");
          })
        );
      
      });
      

      这将删除所有内容,直到第一个 . 是数据库前缀。以防万一您的集合名称中包含 .。

      【讨论】:

      • 谢谢!太好了!
      猜你喜欢
      • 1970-01-01
      • 2013-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-27
      • 2021-05-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多