[英]Mongoose: update Array with item-wise maximum
null
upon instantiation?在 Mongoose 中,如何使用 item-wise max 更新 Array 属性,并在实例化时默认为null
?I have a Mongodb collection of timeseries where values are stored in a fixed-length array (1 item per minute, 1 document per day).我有一个 Mongodb 时间序列集合,其中值存储在固定长度的数组中(每分钟 1 个项目,每天 1 个文档)。
{
'series': '#1',
'values': [null, null, 1, 2, 3, -4, ... ] //24h*60min=1440 items
}
I am doing computations on ~x000 timeseries on a rather high frequency (100ms), and I want to store the maximum that each of these series met during every minute.我正在以相当高的频率(100 毫秒)对 ~x000 时间序列进行计算,并且我想存储每个序列在每分钟内遇到的最大值。 For some reason, when I update the documents, Mongoose transforms the .values
property into an object, which is more space-consuming and less efficient for my use.出于某种原因,当我更新文档时,Mongoose 将.values
属性转换为一个对象,这对我来说更占用空间且效率更低。
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/test_db');
const TestSchema = new mongoose.Schema({
series: String,
values: {type: Array, default: Array(5).fill(null), required: true},
});
const Test = mongoose.model('Test', TestSchema);
async function update({series, values}){ //called every minute or so
let updated = { };
for (let {i, v} of values) {
if (updated[`values.${i}`] && updated[`values.${i}`]<v) updated[`values.${i}`]= v;
if (!updated[`values.${i}`]) updated[`values.${i}`]=v;
};
return mongoose.connection.models.Test.updateOne(
{'series':series},
{ '$max': updated },
{ upsert: true, strict: true, new: true}
);
}
async function test_update(){
//get rid of previous tentatives
await mongoose.connection.models.Test.deleteMany({});
let s = new Test({series: '#1'});
await update({series:'#1', values:[{i:3, v:-3},{i:4, v:6},{i:2, v:4}, {i:2, v:7}]});
}
test_update();
I would want my script to return我希望我的脚本返回
{
"_id" : ObjectId("5cb351d9d615cd456bd6a4ed"),
"series" : "#1",
"__v" : 0,
"values" : [null, null, 7, -3, 6]
}
and not the current result below:而不是下面的当前结果:
{
"_id" : ObjectId("5cb351d9d615cd456bd6a4ed"),
"series" : "#1",
"__v" : 0,
"values" : { //values is an Object, not an Array
"2" : 7,
"3" : -3,
"4" : 6
}
}
Thanks!谢谢!
`I THINK it may be your schema `我认为这可能是你的模式
Instead of:代替:
const TestSchema = new mongoose.Schema({
series: String,
values: {type: Array, default: Array(5).fill(null), required: true},
});
You should make values
an array of numbers like this你应该让values
像这样的数字数组
const TestSchema = new mongoose.Schema({
series: String,
values: {type: [Number], default: Array(5).fill(null), required: true},
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.