You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从MongoDB的LastUpdate日期字符串字段提取月份并与当月匹配?

Solution: Compare Month from String Date Field in MongoDB

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")—DD stands for day of the year, not day of the month. You should use dd instead to get the correct date format (yyyy-MM-dd), otherwise your date parsing will be wrong.


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<>());

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 22:12:27