0

How to print or log real executed query statements, such as django insert, query and other SQL statements will be logged。I searched the documentation of both libraries and found nothing about this.

I want something similar to django in that I can execute any query such as User.object.filter(name='123').values("id", "phone") and log the actual execution statement of this query: select id, phone from auth_user where name='123'

张豪飞
  • 1
  • 2
  • Be more specific. – dpapadopoulos Nov 19 '19 at 09:55
  • if you are only inserted in listening to `Change` events and you happen to have a cluster i think [MongoDB ChangeStream](https://docs.mongodb.com/manual/changeStreams/#change-streams) is there to help you out. Else for offline, you can look into [Mtools](https://github.com/rueckstiess/mtools). – vikscool Nov 19 '19 at 10:20
  • `pymongo` has a handler to monitor queries: https://api.mongodb.com/python/current/api/pymongo/monitoring.html – Peter Nov 19 '19 at 17:47
  • @Peter As I've tried, monitor does listen for events, but it doesn't get executed queries – 张豪飞 Nov 20 '19 at 01:07
  • Do you use MongoDB or Relational Database? I ask this question because the question tags include `mongodb`, however you would like to get sql like query, but MongoDB has no sql like language support – Peter Nov 20 '19 at 07:54

1 Answers1

0

I believe you have 2 options:

1) use pymongo.monitoring, this link from MongoEngine's doc shows how to configure it.

2) Turn on Profiling with db.setProfilingLevel(2), all queries will then be added to the db.system.profile collection. E.g: executing this db.users.findOne({'name': 'abc'}), will add the following to the db.system.profile collection:

{
    "op" : "query",
    "ns" : "myDb.users",
    "command" : {
        "find" : "users",
        "filter" : {
            "name" : "abc"
        },
        "limit" : 1,
        ....
        "$db" : "myDb"
    },
    "keysExamined" : 0,
    "docsExamined" : 0,
    "cursorExhausted" : true,
    "numYield" : 0,
    "locks" : {...},
    "nreturned" : 0,
    "responseLength" : 83,
    "protocol" : "op_msg",
    "millis" : 0,
    "planSummary" : "EOF",
    ...
    "ts" : ISODate("2019-11-20T19:27:13.297Z"),
    "appName" : "MongoDB Shell",
    "allUsers" : [ ],
    "user" : ""
}

As you can see and unfortunately, its not as practical as a SQL query but the information is there

bagerard
  • 5,681
  • 3
  • 24
  • 48