MongoDB查询:筛选englishTitle以director字段值结尾的记录
englishTitle Ends With the Value of director Got it, let's figure out how to pull off this query! You need to find all documents where the englishTitle field ends exactly with the value stored in the same document's director field—here are the cleanest ways to do it in MongoDB:
Method 1: Use find() with $expr and $endsWith (Simplest Approach)
MongoDB 3.6+ supports the $expr operator, which lets you use aggregation expressions directly in your query filter. The $endsWith aggregation operator is perfect here because it's purpose-built to check if one string ends with another:
db.yourCollectionName.find({ $expr: { $endsWith: ["$englishTitle", "$director"] } })
How this works:
$exprunlocks the ability to reference fields from the same document in the query condition$endsWithtakes two arguments: the string to check ($englishTitle) and the suffix to match ($director)- This will return every document where
englishTitleends exactly with the value indirector—no messy regex needed!
Method 2: Aggregation Pipeline with $match
If you plan to run additional aggregation operations after this query (like sorting, grouping, etc.), you can use the same logic in a $match stage:
db.yourCollectionName.aggregate([ { $match: { $expr: { $endsWith: ["$englishTitle", "$director"] } } } // Add other aggregation stages here if needed ])
Method 3: Regex with $regexMatch (For Edge Cases)
If your director field might contain regex special characters (like ., *, or ?), you'll want to escape those to avoid unexpected matches. Use $regexMatch with $concat and regex escape sequences:
db.yourCollectionName.find({ $expr: { $regexMatch: { input: "$englishTitle", regex: { $concat: [".*\\Q", "$director", "\\E$"] }, options: "" } } })
Breakdown:
\\Qand\\Ewrap thedirectorvalue to treat any special regex characters as literal text- The
$at the end ensures we only match strings that end with thedirectorvalue .*matches any characters before the suffix
Example Match
Using your sample document:
{ title: "Iron Man", director: "Someone Important", englishTitle: "Iron Man Someone Important" }
All three methods will return this document, since englishTitle ends exactly with Someone Important.
内容的提问来源于stack exchange,提问作者Fez Vrasta

