如何基于年月筛选MongoDB中的日期范围文档?
Hey there! The issue here is that you're using $elemMatch incorrectly — that operator is designed for matching elements inside arrays, but your from and to are top-level date fields, not part of an array. That's why your query isn't returning the expected results.
Let's walk through two straightforward solutions to filter documents where the date range (from to to) falls within January 2018:
Approach 1: Exact Date Range Comparison (Most Efficient)
This method is ideal if you have indexes on from or to (it leverages indexes for faster queries). Define the start of January 2018 and the start of February 2018, then query for documents whose entire date range lies within this window:
db.yourCollection.find({ "from": { "$gte": ISODate("2018-01-01T00:00:00Z") }, "to": { "$lt": ISODate("2018-02-01T00:00:00Z") } })
This will return exactly the last two documents in your sample data, since their from and to dates are fully contained within January 2018.
Approach 2: Dynamic Year/Month Check with $expr
If you want to build the query programmatically using input year and month values (instead of hardcoding dates), use $expr with MongoDB's date aggregation operators ($year and $month). Note that MongoDB's $month returns 1 for January (not "01"):
db.yourCollection.find({ "$expr": { "$and": [ { "$eq": [{ "$year": "$from" }, 2018] }, { "$eq": [{ "$month": "$from" }, 1] }, { "$eq": [{ "$year": "$to" }, 2018] }, { "$eq": [{ "$month": "$to" }, 1] } ] } })
This checks that both the from and to dates belong to January 2018, matching your target documents.
Bonus: Matching Overlapping Date Ranges
If your requirement was broader (e.g., include documents where the date range overlaps with January 2018, even if it starts in December 2017 or ends in February 2018), use this query:
db.yourCollection.find({ "from": { "$lt": ISODate("2018-02-01T00:00:00Z") }, "to": { "$gte": ISODate("2018-01-01T00:00:00Z") } })
This covers all cases where the document's time range and January 2018 share any overlap.
Just replace yourCollection with the actual name of your MongoDB collection, and you'll get the results you need!
内容的提问来源于stack exchange,提问作者Harsh Patel

