I'm building an Expense Tracker web app using Java Servlets and MongoDB. I want to filter expense documents based on user
and category
(e.g., user: "chir", category: "education").
However, when I run the code below, MongoDB returns all documents instead of just the ones that match the filter.
Here’s the code I’m using in the servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); try { String user = request.getParameter("username"); String category = request.getParameter("category"); if (user == null || user.isEmpty()) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); out.println(gson.toJson(new ResponseMessage("❌ User parameter is required"))); return; } // ✅ Build MongoDB query Document query = new Document("user", user); if (category != null && !category.trim().isEmpty()) { query.append("category", category.trim()); } System.out.println("📡 QUERY => " + query.toJson()); List<Document> expensesList = new ArrayList<>(); // ✅ Double check this is correct collection! try (MongoCursor<Document> cursor = expenseCollection.find(query).iterator()) { while (cursor.hasNext()) { Document doc = cursor.next(); System.out.println("✅ Found: " + doc.toJson()); expensesList.add(doc); } } response.setStatus(HttpServletResponse.SC_OK); out.println(gson.toJson(expensesList)); } catch (Exception e) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); out.println(gson.toJson(new ResponseMessage("❌ Error fetching expenses: " + e.getMessage()))); } }
Here’s an example document from my MongoDB collection:{"_id": { "$oid": "someid" },"user": "chir","category": "education","amount": 1000}Despite this, the query returns all documents. I've printed the filter and it looks correct. I also tested similar queries in MongoDB Compass and they work there.
I expected the find()
function to return only the documents that match both the user
and category
.
I tried:
- Verifying the database connection
- Printing the query object (
filter.toJson()
) - Hardcoding the filter values
- Running the same query in MongoDB Compass (works fine there)
Still, the query from Java returns all documents regardless of the filter.
Is there something I'm missing in how the Java MongoDB driver processes filters in a servlet?Environment:
- Java 23
- MongoDB Driver:
org.mongodb:mongodb-driver-sync:4.11.1
- Servlet running on Apache Tomcat/10.1.39 (2)