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

MongoDB嵌套对象查询求助:检索value以'-'开头的文档

MongoDB Query: Find Documents with Nested Array Element Matching Value Pattern

Let's break down how to fix your query and get the results you need.

The Problem with Your Original Query

Your current query is using $elemMatch in the projection (the second argument of find()) instead of the query filter (the first argument). That means it's only trying to shape the output documents, not filter which documents are returned. So it's not actually selecting the documents that meet your criteria—it's just modifying how matching documents are displayed.

The Correct Query

To filter documents where:

  1. departureDate equals "2020-10-09"
  2. There's an element in travelerCounts with travelCountType: "ActualCapacity"
  3. That same travelerCounts element has a counts sub-array with an object where value starts with -

Use this query:

db.myCollection.find({
  departureDate: "2020-10-09",
  travelerCounts: {
    $elemMatch: {
      travelCountType: "ActualCapacity",
      counts: {
        $elemMatch: {
          value: { $regex: /^-/ }
        }
      }
    }
  }
})

How This Works

  • The outer $elemMatch on travelerCounts ensures we're looking at the same array element that has both travelCountType: "ActualCapacity" and the matching counts sub-element. Without $elemMatch, MongoDB would match documents where any travelerCounts element has the right type, and any (possibly different) travelerCounts element has the matching counts value—which isn't what you want.
  • The inner $elemMatch on counts targets the specific sub-array element where value starts with -, using the regex ^- to match the start of the string.

Optional: Project Only the Matching Elements (If Needed)

If you also want the output to only include the matching travelerCounts elements (instead of the entire array), you can combine the filter with a projection:

db.myCollection.find(
  {
    departureDate: "2020-10-09",
    travelerCounts: {
      $elemMatch: {
        travelCountType: "ActualCapacity",
        counts: { $elemMatch: { value: { $regex: /^-/ } } }
      }
    }
  },
  {
    "travelerCounts.$": 1, // Returns only the first matching travelerCounts element
    departureDate: 1,
    _id: 1
  }
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 14:17:53