MongoDB嵌入式搜索问题:如何匹配departures的scheduledTimeLocal字段
departures.scheduledTimeLocal Let's break down why your initial queries weren't working and get you the right results.
The Core Issue: Incorrect Field Path
Looking at your document structure, each entry in the departures array is an object that contains a movement sub-object—that's where scheduledTimeLocal lives. Your first query used departures.scheduledTimeLocal, which skips the movement layer entirely, so MongoDB couldn't find the field you were targeting.
1. Fuzzy Match for a Specific Date
If you want to find all documents where any departure has a scheduledTimeLocal containing "2020-05-09", use the corrected field path with your regex:
db.schedule.find({ "departures.movement.scheduledTimeLocal": /2020-05-09/ })
This will match any departure time that starts with (or includes) that date string.
2. Exact Match for a Full Time String
Your nested $elemMatch approach was overcomplicating things—since each departures element is an object (not another array), you only need one $elemMatch to target the movement.scheduledTimeLocal field:
db.schedule.find({ "departures": { $elemMatch: { "movement.scheduledTimeLocal": "2020-05-09 10:40+01:00" } } })
This will return documents where at least one departure entry matches that exact time string.
Bonus: Return Only Matching Departure Entries
If you don't want the entire document (just the specific departure that matched your query), use a projection with the positional $ operator:
db.schedule.find( { "departures.movement.scheduledTimeLocal": /2020-05-09/ }, { "departures.$": 1 } )
This will filter the departures array to only include the first matching entry.
内容的提问来源于stack exchange,提问作者Scotty

