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

MongoDB查询:筛选englishTitle以director字段值结尾的记录

How to Query MongoDB Documents Where 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:

  • $expr unlocks the ability to reference fields from the same document in the query condition
  • $endsWith takes two arguments: the string to check ($englishTitle) and the suffix to match ($director)
  • This will return every document where englishTitle ends exactly with the value in director—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:

  • \\Q and \\E wrap the director value to treat any special regex characters as literal text
  • The $ at the end ensures we only match strings that end with the director value
  • .* 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:14:56