【问题标题】:How to find all documents having an identical values in two fields with MongoDB?如何使用 MongoDB 在两个字段中查找具有相同值的所有文档?
【发布时间】:2015-08-29 17:25:49
【问题描述】:
Given that new Documents and querys:
{
    "_id" : ObjectId("55803fd1cc0c9aa090e608be"),
    "song_name" : "Mickey is good",
    "time" : "3.56",
    "artist" : "Mickey"
}


{
    "_id" : ObjectId("55803fd1cc0c9aa090e608bf"),
    "song_name" : "Love is nothing",
    "time" : "5.56",
    "artist" : "Jimmy"
}

我需要找出哪些歌曲的标题与艺术家姓名相同。 我努力了: db.myCollection.find( { $where: "this.artist == /this.song_name/" } );

但没有成功。请帮忙`

【问题讨论】:

  • 到目前为止你做了什么,请分享...
  • 我已经用我目前所做的修改了我的查询..

标签: regex mongodb mongodb-query


【解决方案1】:

如果我理解的很好,你需要找到所有songs whose title contains the name of the artist。你不需要一个正则表达式1。使用indexOf 进行简单测试就足够了。鉴于您的样本数据:

> db.test.find({$where:
      "this.song_name.toLowerCase().indexOf(this.artist.toLowerCase()) > -1"
})

{ "_id" : ObjectId("557ccec684ee2ba0375f4fcf"),
  "song_name" : "Mickey is good",
  "time" : "3.56",
  "artist" : "Mickey" }

如果您确实需要找到标题与艺术家姓名相同的歌曲(您的示例数据中没有这样的文档),您只需编写:

> db.test.find({$where:
      "this.song_name.toLowerCase() == this.artist.toLowerCase()"
})

{ "_id" : ObjectId("557cd12284ee2ba0375f4fd1"),
  "song_name" : "The Monkeys",
  "artist" : "The Monkeys" }

请注意,无论哪种情况,我都使用toLowerCase() 对字符串进行了规范化。根据您的用例,您可能需要比这更复杂的东西。比如需要匹配"You and Me" by "You+Me"。


1如果艺术家姓名包含元字符或量词,则在此处使用正则表达式甚至可能有害。例如,给定艺术家名称 “You+Me”,此处的 + 将被解释为 1 次或多次出现前面的字符。所以,匹配 "YouMe", "YouuuuuMe" 但不 原始字符串 "You+Me".

【讨论】:

    【解决方案2】:

    分隔符内的任何内容都被视为“字符串”,不再是变量。同样在“右侧,此比较无效。所以改为这样做

    db.test.find({ "$where": " return new RegExp(this.artist,i).test(this.song_name);" })
    

    所以RegExp() 从变量编译一个模式,而// 认为所有包含在字符串文字中。 .test() 方法是您如何使用正则表达式与内容进行比较以获得“布尔”结果。

    确实,.indeOf()“应该”比基本字符串的正则表达式更快,但是如果您需要不区分大小写的比较,那么 .toLowerCase() 或 .toUpperCase() 会引入自己的另一个成本,因此丢失了可忽略的差异.

    我也觉得它看起来更整洁。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-24
      • 1970-01-01
      • 2018-04-21
      • 2021-05-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多