gpt4 book ai didi

node.js - 更新 Mongoose 对象数组中的多个对象

转载 作者:太空宇宙 更新时间:2023-11-04 00:07:46 24 4
gpt4 key购买 nike

我的架构如下:

const UserSchema = new mongoose.Schema({
skills: [{
_id: false,
name: String,
level: Number,
exp: Number
}]
});

示例文档如下:

{
"_id": {
"$oid": "5b0941419703f80a121c44df"
},
"skills": [
{
"name": "woodcutting",
"exp": 1110,
"level": 1
},
{
"name": "smithing",
"level": 0,
"exp": 0
},
{
"name": "reading",
"level": 0,
"exp": 0
},
{
"name": "writing",
"level": 0,
"exp": 0
}
]
}

所以我只需要在一个查询中更新木工和锻造的经验和水平,是否可能,如果可能,如何?或者我需要更改所有数组并用它的技能值设置(替换)吗?

最佳答案

您可以使用arrayFilters从 mongodb 3.6 开始

db.collection.update(
{ },
{ "$set": {
"skills.$[skill1].exp": "your_value",
"skills.$[skill2].level": "your_value",
"skills.$[skill2].exp": "your_value",
"skills.$[skill1].level": "your_value"
}},
{ "arrayFilters": [{ "skill1.name": "woodcutting", "skill2.name": "smithing" }] }
)

关于node.js - 更新 Mongoose 对象数组中的多个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51444204/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com