查找字段以其他字段

时间:2018-01-05 12:46:30

标签: mongodb

我有titledirectorenglishTitle字段。

{
  title: "Iron Man",
  director: "Someone Important",
  englishTitle: "Iron Man Someone Important"
}

我需要查找englishTitledirector的值结尾的所有记录。

如何使用MongoDB执行此类查询?

1 个答案:

答案 0 :(得分:1)

如此处所述,您可以使用正则表达式:https://docs.mongodb.com/manual/reference/operator/query/regex/

在你的情况下,它将是

{ englishTitle: { $regex: /^.*director$/ } }

为了找到导演的价值,我想你可以使用" $ where"

https://docs.mongodb.com/manual/reference/operator/query/where/

db.myCollection.find( function() { 
  var possibleDirector = this.englishTitle.substr(this.englishTitle.length - 1 - this.director.length);
  return (possibleDirector === this.director);
} );

(也许它需要很少的抛光,比如检查长度以不在substr中获得负值)