Mongodb中如何将两个键组合成一个新对象? [英] How can two keys be combined into one new object in Mongodb?

查看:49
本文介绍了Mongodb中如何将两个键组合成一个新对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的文档示例.

{
    _id: '1',
    card: [
        {
            'expiration_month': '10',
            'expiration_year': '2017'
        },
        {
            'expiration_month': '01',
            'expiration_year': '2015'
        },
    ]
}

我想将月份和年份组合成一个日期对象,并将其存储在这些键已经存储在其中的同一个对象中.

I want to combine the month and year into a date object and store it in the same object these keys are already stored in.

所以它看起来像这样 expires 实际上是一个日期对象.

So it would look like this where expires would actually be a date object.

{
    _id: '1',
    card: [
        {
            'expiration_month': '10',
            'expiration_year': '2017',
            expires: {                
            }
        },
        {
            'expiration_month': '01',
            'expiration_year': '2015',
            expires: {                
            }
        }
    ]
}

我试过了,但我知道这是错误的.

I've tried this, but I know it is wrong.

db.collection.update({'card.expires': {$exists: false}}, { $set: moment(new Date(card.expiration_year + '-' + card.expiration_month)) })

推荐答案

我会这样做:

db.yourcollection.find().snapshot().forEach(
  function (e) {
    var saveChanges = false;

    if(e.cards && e.cards.length > 0){
        for(var i=0; i < e.cards.length; i++){
            if(e.cards[i].expiration_month && e.cards[i].expiration_year){
                e.cards[i].expires = new Date(e.cards[i].expiration_year, e.cards[i].expiration_month, 1);

                saveChanges = true;
            }
        }
    }
    if(saveChanges) db.yourcollection.save(e);
  }
)

这篇关于Mongodb中如何将两个键组合成一个新对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆