Should I access mongodb directly? Should I access mongodb directly? mongodb mongodb

Should I access mongodb directly?


Should we access it directly

You definitely do not want to expose your MongoDB server(s) to the Android application directly, especially if the application will have a user role allowing write access to the database. Anyone with access to the Android app could potentially discover and extract those credentials, and if your Android app is designed to connect from a wider network this exposes your MongoDB server unnecessarily. You may also be opening your MongoDB server to possible denial-of-service attacks or rogue queries.

The MongoDB documentation has a detailed section on Security Concepts including network exposure and security. Best practice for any database deployment is to limit the range of network addresses that can connect directly. Generally direct connections should be limited to your application servers and monitoring apps, which are probably hosted within the same network infrastructure.

make a PHP script, which would access it and return required results in JSON?

Yes, a recommended approach would be to write your own interface which provides a suitable API and authentication controls. You should be able to find a PHP framework and/or libraries to minimise the amount of custom code you have to write (eg. REST, JSON, Oauth).

The interface you implement can:

  • put some constraints on the type of queries that end users can run (only what you provide, rather than the full MongoDB API)
  • allow the application to authenticate with appropriate user privileges without having the database credentials embedded in the Android app
  • add additional user security such as token-based OAuth or Twitter/Facebook authentication
  • abstract the endpoint that the Android app connects to (your web interface) from the infrastructure detail of your MongoDB deployment
  • potentially include caching for common queries or session data


I would pick the option of creating the PHP script that will handle all the logic and data filteration, send back as JSON response to be ready for the application.

as marked in bold, that will allow you not to worry about filter the data in your client "android application" side, and leave all the dirty work to be done on the server side.


There is a two options

  1. Make an API service that will contains all CRUD operations so you
    will be able to call from you application.

  2. You are able to access directly via Java MongoDb Driver. Readmore here how to get start with java mongodb driver.