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

如何在MongoDB中筛选数组指定类型的数据并二次过滤?

Ah, I see the issue here! Your current query is applying the team filter to all document types, not just the 'TEAM' ones. That's why you're getting no results—PUBLIC and PRIVATE events likely don't have that specific team ID attached, so they're being excluded entirely, and maybe there are no TEAM events that meet the "finished" criteria at the same time.

Let's fix this by structuring the query to only enforce the team ID check when the event type is 'TEAM'. Here's the corrected query:

db.event.find({
  // Keep your original "event is finished" condition intact
  $or: [
    { date: { $lte: new Date() } }, // Using new Date() directly is better than toISOString()—MongoDB stores dates as Date objects, so direct comparison is more reliable
    { status: 'DONE' }
  ],
  // Nested $or to handle type-specific filters
  $or: [
    { type: 'PUBLIC' },          // Include all finished PUBLIC events (no team check needed)
    { type: 'PRIVATE' },         // Include all finished PRIVATE events (no team check needed)
    {                            // Only include finished TEAM events that match your specified team ID
      type: 'TEAM',
      team: ObjectId("512e28984815cbfcb21646a7")
    }
  ]
})

Why this works:

  • The first $or ensures we only pull events that are either past their scheduled date or marked as 'DONE'—your core "finished event" logic stays exactly as you intended.
  • The second $or splits the type requirements logically:
    • For PUBLIC/PRIVATE events: we only check that their type matches, no team ID constraint applies.
    • For TEAM events: we require both the type to be 'TEAM' and the team field to match your specified ObjectId.

Quick optimization note:

I swapped new Date().toISOString() for new Date() because MongoDB stores dates as BSON Date objects. Comparing a Date object directly to your stored date field avoids potential time zone or string-formatting issues that can come from comparing date strings.

内容的提问来源于stack exchange,提问作者Salma

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 19:52:34