source

Mongodb native nodejs 드라이버에 컬렉션이 있는지 확인하는 방법은 무엇입니까?

nicesource 2023. 5. 9. 22:49
반응형

Mongodb native nodejs 드라이버에 컬렉션이 있는지 확인하는 방법은 무엇입니까?

특정 데이터베이스에 컬렉션이 있는지 확인하고 없으면 만들어야 합니다.나는 그것을 알고 있습니다.

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

수집품의 유무 확인collName생성 및 세트 전에error하지만 그것을 확인하기 위해서는 독립적인 기능이 필요합니다.

원어민 운전자의 운전 방법Db개체는 선택적인 컬렉션 이름 필터를 첫 번째 매개 변수로 사용하여 컬렉션의 존재를 확인할 수 있습니다.

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

2.x 버전의 MongoDB 네이티브 드라이버에서는collectionNames은 에서 필터를 수락하고 커서를 반환하는 것으로 대체되었으므로 다음과 같이 수행할 수 있습니다.

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

mongo 네이티브 드라이버와 Node.js 7.6+를 사용하여 다음을 사용합니다.

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

편집

@Matt Cochrane가 언급했듯이,collection.s.name@Johnny처럼 더 이상 사용할 수 없습니다.HK와 @weekens는 올바른 방법은 이 방법을 사용하는 것이라고 지적합니다.

const client = new MongoClient(connectionString, { useUnifiedTopology: true });
await client.connect();
const collections = await client.db().listCollections().toArray();
const collectionNames = collections.map(c => c.name);

listCollection()선택적 필터를 사용합니다.

MongoDB 3.0 이상에서는 데이터베이스의 모든 컬렉션을 나열하는 명령을 실행해야 합니다.

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

조회는 하지만system.namespaces기본 저장 엔진(MMAPv1)을 사용하는 경우에도 계속 작동하지만, WiredTiger와 같은 다른 엔진에서는 작동하지 않습니다.

MongoDB 3.0 이전에는 다음을 수행해야 합니다.

쿼리할 수 있습니다.system.namespaces컬렉션:

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

예:

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

반환되는 항목:

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

물론, 아무것도.

참고 항목: https://github.com/mongodb/specifications/blob/master/source/enumerate-collections.rst

MongoDB 3.0부터는 다음을 간단하게 실행할 수 있습니다.

db.getCollectionNames()

현재 데이터베이스에 있는 모든 컬렉션의 이름을 가진 배열을 반환합니다.

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

Mongo DB Documentation을 선택하거나 db.getCollection을 사용할 수도 있습니다.각 컬렉션에 대한 추가 정보가 필요한 경우 정보()

이제 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;
    }));
  });
}

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")  
  }); 
});

사실, 이것은 나에게 효과가 있습니다.

  await db.createCollection(name, function (err, res) {
    if (err) {
        //console.log(err);
        if (err.codeName =="NamespaceExists") {
            console.log("Already Exists Collection  : " + name + "");
            return;
        }
    }
    console.log("Collection created! : "+name+"");

});

3.6.* 릴리즈와 함께 작동하는 업데이트된 답변입니다.

/**
 * Checks if a collection exists in a mongo database.
 * 
 * @param db a mongo db object.  eg.
 *    client = await MongoClient.connect(uri);
 *    db = client.db();
 * @param collectionName the name of the collection to search for
 * @returns {Promise<boolean>}
 */
async function doesCollectionExistInDb(db, collectionName) {
  const collections = await db.collections();
  return collections.some(
      (collection) => collection.collectionName === collectionName
  );
}

...

if (await doesCollectionExistInDb(db, 'products')) {
   // Do something, such as create a new collection
}

collection.collectionName는 다음 웹 사이트에서 찾을 수 있는 문서화된 수집 api의 일부입니다. http://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#collectionName

mongodb 라이브러리(v3.6.3)가 있는 nodejs의 경우 그것이 내가 작동하는 유일한 방법입니다.

const collectionName = 'products'
const exists = (await (await db.listCollections().toArray()).findIndex((item) => item.name === collectionName) !== -1)
console.log(exists)

다른 사람들을 돕는 희망

비동기 TypeScript 함수:

/**
 * Predicate function that checks if a collection exists in a given MongoDB database
 *
 * @param {Db} db Mongo database instance
 * @param {string} collectionName Name of collection
 *
 * @returns {boolean} true if collection exists, false otherwise
 */
export const doesCollectionExist = async (db: Db, collectionName: string): Promise<boolean> => {
  const cursor = db.listCollections({ name: collectionName })
  const result = await cursor.hasNext()
  await cursor.close()

  return result
}

질문은 네이티브 드라이버에 대한 것이지만, 저는 이것을 어떻게 하는지 찾아 여기에 왔습니다.pymongo은.보통pymongo의 api와 하지만 이 api는 JS api입니다collection_names:JohnnyHK'응답' 대신 첫 번째 인수는 부울(시스템 컬렉션을 포함할지 여부)입니다.문자열이 다음 값으로 평가되므로True이것은 혼란스러울 수 있습니다.그래서 저는 이것이 미래의 독자들에게 도움이 되기를 바랍니다.

import pymongo

cl = pymongo.MongoClient()
db = cl['my-db']
if 'my-col' in db.collection_names(False):
   ...
/* set database */
let db          = client.db( 'crud' )

/* set collection */
let collection  = db.collection( 'categories' )

/* set query */
collection.find( {} ).toArray( ( err, result ) => {

if ( result.length > 0 )
{
    console.log("Exist");
}
else
{
    console.log("Not Exist");

    // create collection
}

}

언급URL : https://stackoverflow.com/questions/21023982/how-to-check-if-a-collection-exists-in-mongodb-native-nodejs-driver

반응형