Asked  7 Months ago    Answers:  5   Viewed   38 times

I am using PHP to connect with MongoDB. My code is as follows.

// connect
$m = new MongoClient($con_string); // connect to a remote host at a given port
$db = $m->main;

$customers = $db->customer->find();

i want to return $customers collection as json document to my HTML. How can i do this?

 Answers

63

You can do this two ways:

echo json_encode(iterator_to_array($customers));

or you can manually scroll through it:

foreach($customers as $k => $row){
    echo json_encode($row);
}

Each of MongoDBs objects should have their __toString() methods correctly implemented to bring back the representation of the value.

Wednesday, March 31, 2021
 
ritch
answered 7 Months ago
12

Following on from the question you linked:

db.documents.find({"type": "chair"}).forEach(function(data) {   
    db.documents.update({_id:data._id},
                       {$set:{'versions.0.content.axdducvoxb':
                               parseFloat(data.versions.0.content.axdducvoxb)}}); 
})

Would be:

foreach($db->documents->find(array("type" => "chair")) as $document){
    $db->documents->update(
        array('_id' => $document['_id']),
        array(
            '$set' => array(
                'versions.0.content.axdducvoxb' => floatval($document['versions'][0]['content']['axdducvoxb'])
            )
        )
    );
}

There done. good answer

Wednesday, March 31, 2021
 
muaddhib
answered 7 Months ago
78

You can't use a single aggregate() to do two grouped counts with your desired result format. Once the data has been grouped the first time you no longer have the details needed to create the second count.

The straightforward approach is to do two queries, as you are already doing ;-).

Thoughts on alternatives

If you really wanted to get the information in one aggregation query you could group on both fields and then do some manipulation in your application code. With two fields in the group _id, results are going to be every combination of group_name and status.

Example using the mongo shell :

db.users.aggregate(
    { $group: {
         _id: { group_name: "$group_name", status: "$status" },
         'total_sum': { $sum: 1 }
    }}
)

That doesn't seem particularly efficient and lends itself to some convoluted application code because you have to iterate the results twice to get the expected groupings.

If you only wanted the unique names for each group instead of the names + counts, you could use $addToSet in a single group.

The other obvious alternative would be to do the grouping in your application code. Do a single find() projecting only the group_name and status fields, and build up your count arrays as you iterate the results.

Saturday, May 29, 2021
 
felipsmartins
answered 5 Months ago
37

Add the below dependency to your pom.xml:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.5.0</version>
</dependency>
Wednesday, June 9, 2021
 
Semirix
answered 5 Months ago
88

Since you post does not mention a working PHP file, I will include it for the sake of completeness. This could be a long (long) post....

So, first. This is an example of a PHP file that is stored with the name my_test.php in at this location: c:wampwwwsome_folder_namemy_test.php (Please see the edit history for the code)

Now, let me explain the important portions of this PHP. These parameters should be configured to use your settings:

$DB_HOST = 'YOUR_IP_ADDRESS';
$DB_UNAME = 'MYSQL_USERNAME';
$DB_PWD = 'MYSQL_USER'S_PASSWORD';
$DB_DATABASE = 'DATABASE_NAME';

The IP Address should be either localhost or the IP address of the computer hosting the MySQL database. Preferably an IP address so you can test on physical devices. using localhost would work only on Virtual Devices.

Next up is adding the columns to an array that will construct a single record (row) in the JSON response. Take a look at this line for example:

$stuff["id"] = $row['id'];

The $stuff["id"] will basically become the tag in the resulting JSON Object whereas the $row['id'] is what indicates the column name from your DB's table. So the $row["...."] has to be identical to the column names in the DB table. While the $stuff["...."] can be just about anything. As long as it makes sense to you.

This line echo(json_encode($response)); will convert the response into a JSON format.

Now lets look at the Java code. First up in this is a class that will help you parse through the result. It was taken off a tutorial off a website (I don't remember which). Just copy an paste the following code in a Java class. No need to change anything in this file. Do give it a good read to understand how it works. I have it named JSONParser (Please see the edit history for the code):

Finally, how would to actually get the resulting JSON and parse it in an Activity / Fragment.

I parse the data in an AsyncTask, which is required anyway considering you will be performing a network operation. (Please see the edit history for the code)

Points to note in this Java:

  1. This String URL_TO_PHP = "http://IP_ADDRESS/some_folder_name/my_test.php"; needs to have either an IP address such as 192.168.0.x or if you are testing on a virtual device, it should be 10.0.2.2. The earlier (192..) won't work on an emulator and the later (10.0...) won't work on a physical device.
  2. In this: String TAG_STUFF = "stuff";, the "stuff" corresponds with this from the PHP file: $response["stuff"] = array();. The TAG_STUFF should basically use whats in $response["stuff"].

Hope all the above makes sense. Comment if you need help. ;-)

UPDATED WITH WORKING SOLUTION:

This is very weird indeed. But, I have a working solution. When using the OP's code, the application indeed crashes. For lack of time to test why it crashes, I am instead posting a solution directly.

First, instead of keeping testing as an independent class, create it as an inner class back in the MainActivity.

class testing extends AsyncTask<Void, Void, Void>   {
....
}

Second, declare the variables globally (the jParser, URL_TO_PHP, etc), as against the current declarations before the onPreExecute(). See the complete solution below for clarity...

public class MainActivity extends Activity {

    JSONParser jParser;
    String URL_TO_PHP = "http://testbox.site50.net/test.php";
    String TAG_SUCCESS = "success";
    String TAG_STUFF = "stuff";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    ....

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button1:
                new testing().execute();
                break;
            default:
                break;
        }

    }

    private class testing extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Void... args) {

            /* Building Parameters */
            List<NameValuePair> params = new ArrayList<>();

            /* getting JSON string from URL */
            JSONObject json = jParser.makeHttpRequest(URL_TO_PHP, "GET", params);

            try {
                /* Checking for SUCCESS TAG */
                int success = json.getInt(TAG_SUCCESS);
                if (success == 1) {
                    JSONArray JAStuff = json.getJSONArray(TAG_STUFF);

                    /** CHECK THE NUMBER OF RECORDS **/
                    int intStuff = JAStuff.length();

                    if (intStuff != 0) {

                        for (int i = 0; i < JAStuff.length(); i++) {
                            JSONObject JOStuff = JAStuff.getJSONObject(i);
                            Log.e("ALL THE STUFF", JOStuff.toString());
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
        }
    }
}

While testing, I also took a screengrab of the results. Here it is: enter image description here

Again, because I am stretched a little thin at the moment, I won't be able to go find out what really is causing the crash in the OP's code. But it's intriguing enough to find out..

Thursday, August 5, 2021
 
relyt
answered 3 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :