1

I'm trying to access the MongoDB profiler in PHP with the same query I would use in the mongo client:

$db = $mongo->selectDB('myapp_db');
$array = $db->execute('return db.system.profile.find();');
echo '<pre>' . print_r($array, true);

But I get this:

Array
(
    [retval] => Array
        (
            [value] => DBQuery: myapp_db.system.profile -> undefined
        )

    [ok] => 1
)

Profiling is enabled and works fine in the client.

ChocoDeveloper
  • 14,160
  • 26
  • 79
  • 117

2 Answers2

1

Method MongoDB::setProfilingLevel — Sets this database's profiling level

<?php

$dbname = 'students';
$mongo = (new MongoClient());
$db = $mongo->$dbname;

# 0 (off), 1 (queries > 100ms), and 2 (all queries)
$db->setProfilingLevel(2);

# …
# Some queries 
# …

$response = $db->system->profile->find();
foreach ($response as $query) {
    print_r($query);
}

Also:

Vladimir Korshunov
  • 3,090
  • 3
  • 20
  • 25
1

There's no need to execute a query in JavaScript, which blocks the server/database, when you can use PHP itself:

$mongo = new MongoClient();

// Alternatively, use selectCollection from $mongo->myapp_db
$collection = $mongo->selectCollection('myapp_db', 'system.profile');

foreach ($collection->find() as $document) {
   print_r($document);
}

This makes more efficient use of memory, since you can iterate through results instead of fetching the entire MongoDB::execute() response in a single array.

Additionally, your original code returns the cursor (a DBQuery object) from JavaScript. To ensure compatibility with other drivers, you should invoke cursor.toArray() before returning. This is discussed in Sammaye's answer to a similar question here.

Community
  • 1
  • 1
jmikola
  • 6,892
  • 1
  • 31
  • 61