2016-10-02 59 views
1

我集合,其中包含的對象,如這樣的:蒙戈排序的字符串值,實際上是數字

{ 
    "_id" : ObjectId("57f00cf47958af95dca29c0c"), 
    "id" : "...", 
    "threadId" : "...", 
    "ownerEmail" : "[email protected]", 
    "labelIds" : [ 
     ... 
    ], 
    "snippet" : "...", 
    "historyId" : "35699995", 
    "internalDate" : "1422773000000", 
    "headers" : { 
     "from" : "[email protected]", 
     "subject" : "....", 
     "to" : "[email protected]" 
    }, 
    "contents" : { 
     "html" : "...." 
    } 
} 

當訪問的對象,我想iternalDate價值,這應該是整數對它們進行排序,但它是一個字符串。有沒有辦法在讀取時對它們進行排序,即使這些是字符串?按字母順序?或者有沒有辦法將它們無痛地轉換爲整數?

回答

7

在我看來,這裏最好的解決方案是首先將它解析爲一個整數。你可以在JavaScript中使用簡單的腳本來做到這一點,使用mongodb客戶端節點:

db.collection.find({}, {internalDate: 1}).forEach(function(doc) { 
    db.collection.update(
     { _id: doc._id }, 
     { $set: { internalDate: parseInt(doc.internalDate) } } 
    ) 
})