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:
departureDateequals"2020-10-09"- There's an element in
travelerCountswithtravelCountType: "ActualCapacity" - That same
travelerCountselement has acountssub-array with an object wherevaluestarts with-
Use this query:
db.myCollection.find({ departureDate: "2020-10-09", travelerCounts: { $elemMatch: { travelCountType: "ActualCapacity", counts: { $elemMatch: { value: { $regex: /^-/ } } } } } })
How This Works
- The outer
$elemMatchontravelerCountsensures we're looking at the same array element that has bothtravelCountType: "ActualCapacity"and the matchingcountssub-element. Without$elemMatch, MongoDB would match documents where anytravelerCountselement has the right type, and any (possibly different)travelerCountselement has the matchingcountsvalue—which isn't what you want. - The inner
$elemMatchoncountstargets the specific sub-array element wherevaluestarts 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
相关产品推荐
相关产品推荐

