我有这样的模型:
var MyModel = new mongoose.Schema({
key: String,
array_values : [{
value: String,
counter: { type: Number, default: 1}
}];
我需要插入一个键值对,以便:
- 如果没有
key
,则添加一个新文档; - 如果有
key
,则:- 如果
array_values
中有一个value
,则counter
字段的值已增加, - 否则,如果没有这样的
值
,则只是将新对象{key, counter}
添加到array_value
中。
- 如果
例如有一个文档:
{
key: "key",
array_values: [{value: "value", counter: 1}]
}
插入{key: "key", value: "value"}
时应为:
{
key: "key",
array_values: [{value: "value", counter: 2}]
}
插入{key: "key_1", value: "value"}
时,应添加一个文档:
{
key: "key",
array_values: [{value: "value", counter: 1}]
},
{
key: "key_1",
array_values: [{value: "value", counter: 1}]
}
插入{key: "key", value: "value_1"}
时应为:
{
key: "key",
array_values: [
{value: "value", counter: 1},
{value: "value_1", counter: 1}]
}
是否可以使用一个查询来完成此操作?
之前我用的是.findOne({key: 'findingKey'})
,然后处理结果,但是速度很慢,要处理大量的key-value
更新:
这是我尝试做的事情:
我添加了一个静态函数:
MyModel.statics.addKeyValue = async function (key, value) {
let item = await this.findOne({key: key}).exec();
if (item) {
const arr = item.array_values;
let findItem = arr.find((arrItem) => {
return arrItem.value === value;
});
if (findItem !== undefined) {
findItem.count += 1;
} else {
item.array_values.push({value: value, counter: 1});
}
await item.save();
} else {
await this.create({
key : key,
array_values: [{value: value, counter: 1}]
});
}
};
但是插入 17 万个值需要超过 10 个小时
最佳答案
您可以尝试使用以下查询。它将从请求正文中查找具有提供的key的文档,并将根据 mongoose 查询返回的结果进行更新或创建。
MyModel.findOne({key: req.body.key}, (err, result) => {
if (!result) {
result = new Model();
result.key = req.body.key;
result.array_values = [];
}
result.array_values.push(req.body.array_values);
result.save();
})
希望这对您有帮助。
关于javascript - Mongoose 更新和插入数据的复杂查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52585520/