MongoDB中如何仅检索所有字符串列表项均匹配正则表达式的文档
Got it, let's break down how to fix this query. The issue with your initial find statement is that MongoDB's $regex on an array field returns documents where at least one element matches the pattern—not all elements. Here are two reliable ways to get exactly what you need:
Method 1: Use $not + $elemMatch
This approach works by excluding any documents that have even one element in items that doesn't match your regex. In other words, we're saying "find documents where there are no items that don't start with 'a'".
db.collection.find({ items: { $not: { $elemMatch: { $not: /^a/ } } } })
Let's break this logic down:
$elemMatch: { $not: /^a/ }targets documents where at least one item doesn't start with 'a'.- Wrapping that in an outer
$notreverses the check, so we only keep documents where no such non-matching elements exist (meaning every item starts with 'a').
Method 2: Aggregation Pipeline for Explicit Control
If you prefer a more transparent approach (or need to extend this logic later), use the aggregation pipeline to validate the array directly:
db.collection.aggregate([ // Add a temporary field to capture items that don't match the regex { $addFields: { nonMatchingItems: { $filter: { input: "$items", cond: { $not: { $regexMatch: { input: "$$this", regex: /^a/ } } } } } } }, // Keep only documents with zero non-matching items { $match: { nonMatchingItems: { $size: 0 } } }, // Optional: Remove the temporary field from final results { $project: { nonMatchingItems: 0 } } ])
Why Your Previous Attempts Didn't Work
$all: [/^a/]fails because$allchecks that the array contains at least one element matching each condition in the list—not that every element matches the condition. It still returns docs with even one matching item.- Basic
$andusage doesn't help here either, since it doesn't automatically apply the condition to every element in the array.
内容的提问来源于stack exchange,提问作者Alexandre Baron

