如何检查Mongodb本机nodejs驱动程序中是否存在集合?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21023982/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:37:30  来源:igfitidea点击:

How to check if a collection exists in Mongodb native nodejs driver?

node.jsmongodbnode-mongodb-native

提问by Nasser Torabzade

I need to check if a collection exists on a certain database and create it if it doesn't. I know that

我需要检查某个数据库中是否存在集合,如果不存在则创建它。我知道

db.createCollection(collName, {strict:true}, function(error, collection))

checks for existance of collection collNamebefore creating it and sets errorobject. but I need an independent function to check that.

collName在创建集合之前检查集合是否存在并设置error对象。但我需要一个独立的函数来检查。

采纳答案by Derick

In MongoDB 3.0 and later, you have to run a command to list all collections in a database:

在 MongoDB 3.0 及更高版本中,您必须运行命令来列出数据库中的所有集合:

use test;
db.runCommand( { listCollections: 1 } );

Although querying system.namespaceswill still work when you use the default storage engine (MMAPv1), it is not guaranteed to work for other engines, such as WiredTiger.

尽管system.namespaces在使用默认存储引擎 (MMAPv1) 时查询仍然有效,但不能保证它适用于其他引擎,例如 WiredTiger。

Before MongoDB 3.0 you need to do the following:

在 MongoDB 3.0 之前,您需要执行以下操作:

You can query the system.namespacescollection:

您可以查询system.namespaces集合:

use test;
db.system.namespace.find( { name: 'test.' + collName } );

Like in:

像:

db.system.namespaces.find( { name: 'test.testCollection' } );

Which returns:

返回:

{ "name" : "test.testCollection", "options" : { "flags" : 1 } }

Or of course, nothing.

或者当然,什么都没有。

See also: https://github.com/mongodb/specifications/blob/master/source/enumerate-collections.rst

另见:https: //github.com/mongodb/specifications/blob/master/source/enumerate-collections.rst

回答by JohnnyHK

The collectionNamesmethod of the native driver's Dbobject accepts an optional collection name filter as a first parameter to let you check the existence of a collection:

collectionNames机驱动程序Db对象的方法接受一个可选的集合名称过滤器作为第一个参数,让您检查集合的存在:

db.collectionNames(collName, function(err, names) {
    console.log('Exists: ', names.length > 0);
});

In the 2.x version of the MongoDB native driver, collectionNameshas been replaced by listCollectionswhich accepts a filter and returns a cursor so you would do this as:

在 MongoDB 本机驱动程序的 2.x 版本中,collectionNames已被替换为listCollectionswhich 接受过滤器并返回一个游标,因此您可以这样做:

db.listCollections({name: collName})
    .next(function(err, collinfo) {
        if (collinfo) {
            // The collection exists
        }
    });

回答by ChrisV

Using mongo-nativedriver and Node.js7.6+, I use the following:

使用mongo-native驱动程序和Node.js7.6+,我使用以下内容:

const collections = await db.collections();
if (!collections.map(c => c.s.name).includes(collName)) {
    await db.createCollection(collName);
}

回答by Roberto

Since MongoDB 3.0 you can simply run:

从 MongoDB 3.0 开始,您可以简单地运行:

db.getCollectionNames()

which returns an array with the names of all the collections on current database:

它返回一个数组,其中包含当前数据库中所有集合的名称:

[ "employees", "products", "mylogs"]

check Mongo DB Documentation, or you could also use db.getCollectionInfos() if you need more info about each collection

检查Mongo DB Documentation,或者如果您需要有关每个集合的更多信息,也可以使用 db.getCollectionInfos()

回答by weekens

There is now a listCollectionsmethod in Node.js native driver. It returns information on all collections in current database. You can use it to check if a given collection is there:

Node.js 本机驱动程序中现在有一个listCollections方法。它返回有关当前数据库中所有集合的信息。您可以使用它来检查给定的集合是否存在:

collectionExists = function(name, cb) {
  mongoDb.listCollections().toArray(function(err, collections) {
    if (err) return cb(err);

    cb(null, collections.some(function(coll) {
      return coll.name == name;
    }));
  });
}

回答by roscoe_x

If you use mongodb 3.1.10. This is how to check if collections exist.

如果您使用 mongodb 3.1.10。这是检查集合是否存在的方法。

MongoClient.connect(url, { useNewUrlParser: true }, function(err, client) {
  if (err) throw err;

  var dbo = client.db("dbname");
  dbo.listCollections().toArray(function(err, items){
    if (err) throw err;

    console.log(items); 
    if (items.length == 0)
        console.log("No collections in database")  
  }); 
});

回答by dimid

The question refers to the native driver, but I got here searching how to do this in pymongo. Usually pymongo's api is identical to the JS api, but in this case collection_namesdoesn't have an argument for the collection's name (as in JohnnyHK's answer), but rather the first argument is a boolean (whether to include system collections). Since a string evaluates to True, this can be confusing. So I hope this helps future readers:

该问题涉及本机驱动程序,但我来到这里搜索如何在pymongo. 通常pymongo的 api 与 JS api 相同,但在这种情况下collection_names,没有集合名称的参数(如JohnnyHK's answer),而是第一个参数是布尔值(是否包括系统集合)。由于字符串的计算结果为True,因此这可能会令人困惑。所以我希望这对未来的读者有所帮助:

import pymongo

cl = pymongo.MongoClient()
db = cl['my-db']
if 'my-col' in db.collection_names(False):
   ...