简体   繁体   English

如何更改MongoDB中字段的类型

[英]How to change type of a field in MongoDB

Here are my questions: 这是我的问题:

  1. How to change all the string type "NULL" in one field to nulls in null type in MongoDB? 如何在MongoDB中将一个字段中的所有字符串类型“NULL”更改为null类型的null?

  2. How to change all the string type "20xx-xx-xx" in one field to date type in MongoDB? 如何在MongoDB中将一个字段中的所有字符串类型“20xx-xx-xx”更改为日期类型?

db.foo.insert({bar: "NULL", date: "2012-11-30"})
db.foo.insert({bar: "NULL", date: "2010-09-21"})
db.foo.insert({bar: "NOTNULL", date: "2010-09-21"})

How to change all the string type "NULL" in one field to nulls in null type in MongoDB? 如何在MongoDB中将一个字段中的所有字符串类型“NULL”更改为null类型的null?

db.foo.update({bar: "NULL"}, {$set: {bar: null}}, {multi: true})

How to change all the string type "20xx-xx-xx" in one field to date type in MongoDB? 如何在MongoDB中将一个字段中的所有字符串类型“20xx-xx-xx”更改为日期类型?

db.foo.find({date: {$exists: true}}).forEach(
   function(doc) {doc.date = new Date(doc.date); db.foo.save(doc)}
)

Edit 编辑

If for some reason you have problem with default parsing it can be done manually: 如果由于某种原因您遇到默认解析问题,可以手动完成:

Lets assume you have document like this 让我们假设您有这样的文档

doc = {date: "2012-01-30"}

First split string representation on hypens and cast each to integer 首先拆分字符串表示超量并将每个表达式转换为整数

dateArray = doc.date.split('-').map(function(s) { return parseInt(s); })

Substract 1 from month field (months in js are counted from 0) 从月份字段中减去1(js中的月数从0开始计算)

dateArray[1] -= 1

Now we can create new date object. 现在我们可以创建新的日期对象。 There are whoever some things to consider. 有些事情需要考虑。 When you parse string to date, there is assumption that the string represents UTC date when you use this: 解析字符串到日期时,假设使用此字符串时字符串表示UTC日期:

new Date("2012-01-30")

You will get 你会得到

ISODate("2012-01-30T00:00:00Z") 

You can also create Date constructor like this 您也可以像这样创建Date构造函数

new Date(dateArray[0], dateArray[1], dateArray[2])

but it will assume that data is using local tz so and in my case (GMT+1) I get: 但它会假设数据使用本地tz所以在我的情况下(GMT + 1)我得到:

ISODate("2012-01-29T23:00:00Z")

If it is not what you want you can set some fields manually: 如果它不是您想要的,您可以手动设置一些字段:

date = new Date(0) // ISODate("1970-01-01T00:00:00Z")
date.setUTCFullYear(dateArray[0], dateArray[1], dateArray[2])

Now date looks like this: 现在日期看起来像这样:

ISODate("2012-01-30T00:00:00Z")

Wrapping it all together: 将它们全部包装在一起:

db.foo.find({date: {$exists: true}}).forEach(
   function(doc) {
       dateArray = doc.date.split('-').map(function(s) { return parseInt(s); });
       dateArray[1] -= 1;

       date = new Date(0);
       date.setUTCFullYear(dateArray[0], dateArray[1], dateArray[2]);

       doc.date = date;
       db.foo.save(doc)
    }
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM