使用嵌套字段中的值更新字段 [英] Update field with value from a nested field
问题描述
我知道我可以在 update 中使用管道聚合器来用另一个字段的值更新一个值的字段.但是,我的问题是基于嵌套字段的值更新字段值时.更新的结果总是发出带括号的新字段.我不想要括号/数组,我只想要它是一个值.见下面的代码https://mongoplayground.net/p/7ZDP8CYtKK3
I know I can use the pipeline aggregator within update to update the field of one value with the value from another field. However, my issue is when updated a field value based on the value of a nested field. The result of the update always issues the new field with brackets. I don't want brackets/array, I just want it to be a value. See code below https://mongoplayground.net/p/7ZDP8CYtKK3
db={
"players": [
{
"_id": ObjectId("5fba17c1c4566e57fafdcd7e"),
"username": "moshe",
"health": 0,
"maxHealth": 200,
"Chapters": [
{"Cat A": 25,
"Cat B": 100,
"Cat C": 125}]
}
]
}
这是我在下面应用的查询
Here's the query I apply below
db.players.update(
{username: "moshe"},
[{"$set": {"health": "$Chapters.Cat A"}}]
)
结果产生
[{"Chapters": [
{"Cat A": 25,
"Cat B": 100,
"Cat C": 125}],
"_id": ObjectId("5fba17c1c4566e57fafdcd7e"),
"health": [25],
"maxHealth": 200,
"username": "moshe"
}]
我想要的是在没有数组括号的情况下显示健康更新...... health":25
What I want is for the update to health to appear without array brackets as so.... "health":25
这也是一个基于我正在使用的更大的数据库的示例.
Again this is an example based on a much much larger DB I'm working with.
推荐答案
您可以使用 $arrayElemAt 或 $first(v4.4) 运算符从数组中选择第一个元素,
You can use $arrayElemAt or $first(v4.4) operators to select the first element from an array,
db.players.update(
{ username: "moshe" },
[{
"$set": {
"health": {
"$arrayElemAt": ["$Chapters.Cat A", 0]
}
}
}]
)
这篇关于使用嵌套字段中的值更新字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!