If Collection not exists then it does not throw Error, why?

Viewed 196

in java code, I am using the aggregation method. like- mongoTemplate.aggregate(aggregation,Request.class, Response.class).getMappedResults();

and manually I remove the collection and want to it throw error when collection is not exist but with above code return null value and does not throw any error how we can achieve to throw error in case collection not exist and return response if collection exist. and don't want to separate to check collection is exist or not. or mongotemplate does not throw error if collection is not exists

1 Answers

it's by design, if a collection doesn't exist, when you will send a write request, this collection will be created (for a read operation as in your case, it will be just no-op request). You can see this behavior in the shell as well:

mongos> use new_db
switched to db new_db
mongos> show collections  # pay attention that db is empty so no collections   
mongos> db.testColl.insertOne({})
{
        "acknowledged" : true,
        "insertedId" : ObjectId("615a1792e987158566c7a4bf")
}
mongos> show collections  # pay attention that the collection has been created automatically
testColl  
Related