如何从MongoDB的LastUpdate日期字符串字段提取月份并与当月匹配?
Got it, let's break down how to solve this problem—you want to extract the month from your LastUpdate string field and match it against the current month from todaydate. First, a quick critical note:
Important Fix: In your original code, you used
SimpleDateFormat("yyyy-MM-DD")—DDstands for day of the year, not day of the month. You should useddinstead to get the correct date format (yyyy-MM-dd), otherwise your date parsing will be wrong.
Option 1: Filter Directly in MongoDB (Recommended)
Doing the filtering at the database level is way more efficient, especially if you have a large dataset. Since LastUpdate is stored as a string in yyyy-MM-dd format, we can extract the month part directly in the query.
Substring Approach
Use MongoDB's substring operator to pull the 2-digit month from the LastUpdate string (positions 5-6, since indexes start at 0):
// Fix the date format first SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); String todayDate = format.format(new Date()); // Extract current month (e.g., "05" from "2024-05-20") String todayMonth = todayDate.split("-")[1]; // Build the filter to match months Bson monthFilter = Filters.eq(Filters.substring("LastUpdate", 5, 2), todayMonth); ArrayList<Document> activeList = Person_List.find(monthFilter).into(new ArrayList<>());
Split Approach (More Intuitive)
Use $split to break the date string by hyphens, then grab the second element (index 1) which is the month:
// Same setup for todayMonth as above Bson monthFilter = Filters.expr( Filters.eq( new Document("$arrayElemAt", Arrays.asList(new Document("$split", Arrays.asList("$LastUpdate", "-")), 1)), todayMonth ) ); ArrayList<Document> activeList = Person_List.find(monthFilter).into(new ArrayList<>());
Option 2: Filter in Java (Not Recommended for Large Datasets)
If you need to fetch all documents first and filter on the application side, you can do this—just note it's less efficient for big collections:
// Fix date format and get today's month SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); String todayDate = format.format(new Date()); String todayMonth = todayDate.split("-")[1]; // Fetch all documents, then filter in Java ArrayList<Document> allPersons = Person_List.find().into(new ArrayList<>()); ArrayList<Document> activeList = new ArrayList<>(); for (Document person : allPersons) { String lastUpdate = person.getString("LastUpdate"); if (lastUpdate != null) { String lastUpdateMonth = lastUpdate.split("-")[1]; if (todayMonth.equals(lastUpdateMonth)) { activeList.add(person); } } }
Pro Tip: Use MongoDB Date Type Instead
If you can modify your schema, storing LastUpdate as a native MongoDB Date (ISODate) will make date operations way easier. Here's how you'd filter by month then:
// Get current month (Calendar uses 0-indexed months, so add 1) Calendar cal = Calendar.getInstance(); int todayMonthInt = cal.get(Calendar.MONTH) + 1; // Filter using $month operator for Date fields Bson monthFilter = Filters.eq(new Document("$month", "$LastUpdate"), todayMonthInt); ArrayList<Document> activeList = Person_List.find(monthFilter).into(new ArrayList<>());
内容的提问来源于stack exchange,提问作者Prasad Mayya M

