Mongo按实际为数字的字符串值排序 [英] Mongo sort by string value that is actually number
本文介绍了Mongo按实际为数字的字符串值排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含这样的对象的集合:
I have collection that contains objects such as this:
{
"_id" : ObjectId("57f00cf47958af95dca29c0c"),
"id" : "...",
"threadId" : "...",
"ownerEmail" : "...@...",
"labelIds" : [
...
],
"snippet" : "...",
"historyId" : "35699995",
"internalDate" : "1422773000000",
"headers" : {
"from" : "...@...",
"subject" : "....",
"to" : "...@..."
},
"contents" : {
"html" : "...."
}
}
访问对象时,我想通过iternalDate值对它们进行排序,该值应该是整数,但是它是一个字符串.即使它们是字符串,在提取时是否可以对它们进行排序?按字母顺序排列?还是有办法轻松地将它们转换为整数?
When accessing objects, I want to sort them by iternalDate value, which was supposed to be integer, however it is a string. Is there a way to sort them when fetching even if these are strings? By alphabetic order? Or is there a way to convert them to integer painlessly?
推荐答案
在我看来,最好的解决方案是首先将其解析为整数.您可以使用javascript这样的简单脚本,使用mongodb客户端作为节点:
It seems to me that the best solution here would be to parse it first as an integer. You could do it using a simple script in javascript like this, using the mongodb client for node:
db.collection.find({}, {internalDate: 1}).forEach(function(doc) {
db.collection.update(
{ _id: doc._id },
{ $set: { internalDate: parseInt(doc.internalDate) } }
)
})
这篇关于Mongo按实际为数字的字符串值排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文