我想知道如何在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"})

最佳答案

根据您的意思是“单词的最后三个字母”还是“'字段'的最后三个字母”,那么您通常需要一个 $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" }

关于regex - 匹配字符串 "ces"的最后三个字母,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36439225/

10-15 06:03