将所有数组元素的ISO日期转换为mongo 3.4(而不是3.6)中的等效JSON文档

问题描述 投票:0回答:1

假设我的个人资料集合如下所示:

{
_id : ObjectId("59cb823013e825455b1c1a04"),
positions : 
[
    {
        "uid" : 5,
        "startDate" : ISODate("2016-11-30T23:00:00.000Z")
    },
    {
        "uid" : 6,
        "startDate" : ISODate("2011-10-31T23:00:00.000Z")
    }
]
}

我想将位置中的所有startDate字段转换为以下格式:

{
year : 2012,
month : 11,
day : 10
}

我试图运行此查询:

db.profile.find({})
  .forEach(function (doc) {
    doc.positions.forEach(function (position) {
        var year = { $year: position.startDate };
        var month = { $month: position.startDate };
        var day = { $day: position.startDate };
        position.startDate = {
            year : year,
            month : month;
            day : day;
            };
    });
    db.profile.save(doc);
  });

但我收到此错误:错误:字段名称无法以$ [$ year]开头

有这项工作的任何帮助?

mongodb mongodb-query
1个回答
0
投票

使用以下方法解决此问题:

db.profile.find({})
  .forEach(function (doc) {
    doc.positions.forEach(function (position) {
        var year = position.startDate.getFullYear();
        var month = position.startDate.getMonth();
        var day = position.startDate.getDay();
        position.startDate = {
            year : year,
            month : month;
            day : day;
            };
    });
    db.profile.save(doc);
  });
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.