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

MongoDB嵌入式搜索问题:如何匹配departures的scheduledTimeLocal字段

Fixing Your MongoDB Query for 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 15:58:10