问题:使用 Mongo(ose) 从 NumberDecimal 中提取小数

在存储货币值的数值模型中,MongoDB 文档状态:

使用 NumberDecimal() 构造函数从 mongo shell 分配和查询十进制值。

同样,在使用 Morphia Java 库时,BigDecimal 会自动作为 BigDecimal 插入。

我正在使用 Mongoose 在 Node 中查询 Mongo,并尝试提取存储为 NumberDecimal 的字段的数值。但是,该值奇怪地包含在查询结果中,我不确定如何通过 Mongo 或 Mongoose 提取它:

[  
   {  
      "openValue":{  
         "$numberDecimal":"119.931"
      },
      "timestamp":"2017-01-20T10:30:00.000Z"
   },
   {  
      "openValue":{  
         "$numberDecimal":"119.965"
      },
      "timestamp":"2017-01-20T10:31:00.000Z"
   }
]

我读过的一篇文章说在我的应用程序代码中使用parseFloat()将执行我想要的,但是遍历结果以执行此转换效率不高。避免迭代和转换意味着每当我每次想要它们的值时都在 NumberDecimals 上运行该函数,这很烦人。

有没有办法可以使用 Mongodb 或 Mongoose 将上述 JSON 查询结果转换为以下内容?

[  
   {  
      "openValue": 119.931,
      "timestamp":"2017-01-20T10:30:00.000Z"
   },
   {  
      "openValue": 119.965,
      "timestamp":"2017-01-20T10:31:00.000Z"
   },
   {  
      "openValue": 119.975,
      "timestamp":"2017-01-20T10:32:00.000Z"
   }
]

我尝试将字段选择为...openValue.$numberDecimal,但这不起作用。谢谢!

编辑:这是我的猫鼬模式:

var EquityHistoryModel = new Schema({
   _id: {
      equityIdentifier: { type: {
         exchange: { type: String, index: true },
         symbol: { type: String, index: true }
      }, index: true },
      instant: { type: Date, index: true },
      durationMinutes: { type: Number }
   },
   open: { type: mongoose.Schema.Types.Decimal },
   high: { type: mongoose.Schema.Types.Decimal },
   low: { type: mongoose.Schema.Types.Decimal },
   close: { type: mongoose.Schema.Types.Decimal },
   volume: { type: Number },
   isDividendAdjusted: { type: Boolean },
   isSplitAdjusted: { type: Boolean }
}, { collection: 'equityHistories', versionKey: false });

这是上面第一个 JSON 结果的 Mongoose 查询:

mongo.EquityHistoryModel.aggregate([  
   {  
      "$match":{  
         "_id.equityIdentifier.exchange":passed_in,
         "_id.equityIdentifier.symbol":passed_in,
         "_id.instant":passed_in
      }
   },
   {  
      "$project":{  
         "_id":0,
         "openValue":"$open",
         "timestamp":"$_id.instant"
      }
   }
],

解答

也可以覆盖toJSON方法:

// Never return '__v' field and return the 'price' as String in the JSON representation
// Note that this doesn't effect `toObject`
EquityHistoryModel.set('toJSON', {
  getters: true,
  transform: (doc, ret) => {
    if (ret.price) {
      ret.price = ret.price.toString();
    }
    delete ret.__v;
    return ret;
  },
});
Logo

MongoDB社区为您提供最前沿的新闻资讯和知识内容

更多推荐