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.
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.
Explanation: The find() method with no parameters returns all documents from a collection and returns all fields for the documents.
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.
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.
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
}
});
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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With