Reputation: 91
I have a MongoDB collection "cars" and below gives me how many documents exist inside it:
let carsColl = db.getCollection('cars');
carsColl.count();
However, I need to know how many times the cars collection is queried in total ? Also, say if I have two cars x and y, may I know how many SELECT queries executed for 'x' vs 'y' documents?
I checked MongoDB triggers but they can only be created for INSERT, UPDATE, REPLACE and DELETE, but not SELECT.
Any guidance will be of great help.
Upvotes: 2
Views: 571
Reputation: 17915
So from your question basically you're not looking to query documents in a collection rather looking to query on type of operations being done on cars collection i.e; on logs.
Where as your below code will give no.of documents in cars collection :
let carsColl = db.getCollection('cars');
carsColl.count();
As that's not what you're looking for, then try below :
Steps :
Enable Db profiling, by default your DB will log slow running queries that is any query that runs > 100ms, So you need to log all queries in this case. Execute below query to log all queries on DB :
db.setProfilingLevel(2)
Note : Doing this can effect your DB performance as it will be logging all operations, which might become an issue for Prod servers having high amount of DB calls. Ref : manage-the-database-profiler . Also check on how to execute above query as it might need user admin access.
Now once you do above step, You can execute these queries :
To get count of all read queries on collection cars which is inside test DB, try below query. Here op: 'query'
refers to all find calls (Remember that aggregation is different it has op : command
).
db.system.profile.find( { ns : 'test.cars', op: 'query' }).count()
To get count of specific queries : In this case let's say your collection has few documents with a field carType : x
& few others has carType : y
and you're querying on them like this db.cars.find('carType': 'x')
, then :
db.system.profile.find( { ns : 'test.cars', op: 'query' , 'command.filter.carType' : 'x' }).count() // will give you all queries on x
db.system.profile.find( { ns : 'test.cars', op: 'query' , 'command.filter.carType' : 'y' }).count() // will give you all queries on y
Note : Basically you'll be giving your filter query over db.system.profile.find()
to differentiate between your needed finds (Vs) all other find logs.
Upvotes: 1