2016-04-06 43 views
1

我想知道如何在mongodb中使用名稱的最後三個字母來查找某些內容,其結構爲db.collection.find(),謝謝!在最後三個字母中匹配字符串「ces」

{ 
    "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"}) 
+0

在未來將是有益的,包括你的問題,一些數據,實際上將匹配你想要的查詢條件(S)。這裏的''name''字段不會以'ces'結尾,甚至不會在字符串的任何部分包含這些字母。 –

回答

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" } 
相關問題