Home > Blockchain >  Can anyone know if we can tag the MongoDB queries/commands to know which function of the app ran tha
Can anyone know if we can tag the MongoDB queries/commands to know which function of the app ran tha

Time:10-26

I am using the same query (or slightly modified but using the same MongoDB Collection) in various functions and on Mongo Atlas, we get only the collection name and query but don't know which function actually triggered it.

Is there any way to tag the queries with the functions so it can be easy to debug?

CodePudding user response:

Two things come to mind.

The first is the ability to apply a comment to a query:

test> db.foo.find({x:123}).comment("unique identifier xyz");
test> db.system.profile.find().sort({ts:-1}).limit(1)
[
  {
    op: 'query',
    ns: 'test.foo',
    command: {
      find: 'foo',
      filter: { x: 123 },
      comment: 'unique identifier xyz',
      lsid: { id: UUID("6ce75fd2-dd4a-4c4e-9655-b80eca8ef755") },
      '$db': 'test'
    },
    keysExamined: 0,
    docsExamined: 10,
    ...

There is also the ability to apply an appName in the connection string.


Above I demonstrated the database profiler is one place where comments can show up, if configured. The full list of availability is described in the documentation.

For comments:

comment() associates a comment string with the find operation. This can make it easier to track a particular query in the following diagnostic outputs:

  • The system.profile
  • The QUERY log component
  • db.currentOp()

See configure log verbosity for the mongod log, the Database Profiler tutorial, or the db.currentOp() command.

And for appName:

Specify a custom app name. The app name appears in:

  • mongod and mongos logs
  • the currentOp.appName field in the currentOp command and db.currentOp() method output
  • the system.profile.appName field in the database profiler output

The appName connection option is available for:

  • MongoDB Drivers starting in MongoDB 4.0
  • mongosh starting in mongosh 1.1.9
  • MongoDB Compass starting in Compass 1.28.4
  • Related