Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 collName before creating it and sets error object. but I need an independent function to check that.

like image 536
Nasser Torabzade Avatar asked Jan 09 '14 15:01

Nasser Torabzade


People also ask

How do you check if a collection already exists in MongoDB?

The collectionExists method can be used to check whether a collection is present or not: MongoClient mongoClient = new MongoClient("localhost", 27017); DB db = mongoClient. getDB("baeldung"); String testCollectionName = "student"; System.

Which command is used to check the existence of collection is in MongoDB?

Explanation: The find() method with no parameters returns all documents from a collection and returns all fields for the documents.

How do I find a particular collection in MongoDB?

Find() Method. In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents. Cursor means a pointer that points to a document, when we use find() method it returns a pointer on the selected documents and returns one by one.

Does MongoDB Create collection if not exists?

If a collection does not exist, MongoDB creates the collection when you first store data for that collection. You can also explicitly create a collection with various options, such as setting the maximum size or the documentation validation rules.


2 Answers

The collectionNames method of the native driver's Db object accepts an optional collection name filter as a first parameter to let you check the existence of a collection:

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

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

db.listCollections({name: collName})
    .next(function(err, collinfo) {
        if (collinfo) {
            // The collection exists
        }
    });
like image 140
JohnnyHK Avatar answered Oct 19 '22 19:10

JohnnyHK


Using mongo-native driver and Node.js 7.6+, I use the following:

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

EDIT

As @MattCochrane mentions, collection.s.name is no longer available; as @JohnnyHK and @weekens point out, the correct way is to use the listCollections() method:

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() takes an optional filter.

like image 24
ChrisV Avatar answered Oct 19 '22 21:10

ChrisV