【问题标题】:Match string "ces" in the Last Three Letters匹配最后三个字母中的字符串“ces”
【发布时间】:2016-07-26 03:40:55
【问题描述】:

我想知道如何在 mongodb 中仅使用其名称的最后三个字母,结构为 db.collection.find(),谢谢!

  {  
    "address": {
      "building": "1007",
      "coord": [ -73.856077, 40.848447 ],
      "street": "Morris Park Ave",
      "zipcode": "10462"
    },
    "borough": "Bronx",
    "cuisine": "Bakery",
    "grades": [
      { "date": { "$date": 1393804800000 }, "grade": "A", "score": 2 },
      { "date": { "$date": 1378857600000 }, "grade": "A", "score": 6 },
      { "date": { "$date": 1358985600000 }, "grade": "A", "score": 10 },
      { "date": { "$date": 1322006400000 }, "grade": "A", "score": 9 },
      { "date": { "$date": 1299715200000 }, "grade": "B", "score": 14 }
    ],  
    "name": "Morris Park Bake Shop",
    "restaurant_id": "30075445"
  }

我目前的尝试:

db.mycollection.find({},{name:"ces"})

【问题讨论】:

  • 将来,在您的问题中包含一些实际匹配您想要的查询条件的数据会很有帮助。这里的"name" 字段不以"ces" 结尾,甚至在字符串的任何部分都不包含这些字母。

标签: regex mongodb mongodb-query


【解决方案1】:

根据您的意思是“单词的最后三个字母”还是“‘字段’的最后三个字母”,那么您通常需要$regex

关于这些数据:

{ "_id" : ObjectId("570462448c0fd5187b53985a"), "name" : "Bounces" }
{ "_id" : ObjectId("5704624d8c0fd5187b53985b"), "name" : "Something" }
{ "_id" : ObjectId("5704625b8c0fd5187b53985c"), "name" : "Bounces Something" }

然后是“单词”的查询,其中\b表示“单词边界”,在“字符串”表达式中被\转义:

db.collection.find({ "name": { "$regex": "ces\\b" } })

哪些匹配:

{ "_id" : ObjectId("570462448c0fd5187b53985a"), "name" : "Bounces" }
{ "_id" : ObjectId("5704625b8c0fd5187b53985c"), "name" : "Bounces Something" }

或者查询“字段”,其中$表示“从头到尾”:

db.collection.find({ "name": { "$regex": "ces$" } })

哪些匹配:

{ "_id" : ObjectId("570462448c0fd5187b53985a"), "name" : "Bounces" }

【讨论】:

    【解决方案2】:

    尝试以下任何一种:

    • db.hotels.find({name: /ces$/})

    • db.hotels.find({name: {$regex: "ces$"}})

    • db.hotels.find({name: {$regex: /ces$/}})

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-27
      • 2016-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-26
      • 1970-01-01
      相关资源
      最近更新 更多