我使用的是较低版本的 MongoDB,所以
$cond
或 $switch
给了我错误:
MongoServerError:“elems.1.val.$switch”中的美元($)前缀字段“$switch”对于存储无效。
我有一个收藏如下:
{
"attribute": [
{ "type": "ethnicity", "val": "White" },
{ "type": "ethnicity", "val": "Asian" },
{ "type": "Language", "val": "English" }
]
}
我想将种族更新为特定的内容。示例:
亚洲 --> 东亚,
白人 --> 白种人
如何编写查询而不出现此错误?
db.ethnicity.updateMany(
{ "attributes.type": "ethnicity", "attributes.val": { $in: ["asian", "Caucasian"] } },
[
{
$set: {
"attributes.$[elem].val": {
$switch: {
branches: [
{ case: { $eq: [ "asian", "$attributes.$[elem].val" ] }, then: "non-asian" },
{ case: { $eq: [ "Caucasian", "$attributes.$[elem].val" ] }, then: "White" }
],
default: "$attributes.$[elem].val"
}
}
}
}
],
{ arrayFilters: [ { "elem.type": "ethnicity", "elem.val": { $in: ["asian", "Caucasian"] } } ] }
);
请注意,根据您的示例数据和查询,更新查询将不起作用,因为附加数据中不存在
attributes
字段。我认为这是一个拼写错误,attributes
,而不是attribute
。
[
{
attributes: [
{
type: "ethnicity",
val: "White"
},
{
type: "ethnicity",
val: "Asian"
},
{
type: "Language",
val: "English"
}
]
}
]
同时,聚合管道不能与
arrayFilters
一起工作。
您应该使用
$map
运算符迭代 attributes
数组中的每个元素,并使用 val
字段更新每个对象,仅当条件匹配时才会更新。
db.collection.update({
"attributes.type": "ethnicity",
"attributes.val": {
$in: [
"Asian",
"White"
]
}
},
[
{
$set: {
attributes: {
$map: {
input: "$attributes",
in: {
$mergeObjects: [
"$$this",
{
val: {
$switch: {
branches: [
{
case: {
$and: [
{
$eq: [
"ethnicity",
"$$this.type"
]
},
{
$eq: [
"Asian",
"$$this.val"
]
}
]
},
then: "East Asian"
},
{
case: {
$and: [
{
$eq: [
"ethnicity",
"$$this.type"
]
},
{
$eq: [
"Caucasian",
"$$this.val"
]
}
]
},
then: "White"
}
],
default: "$$this.val"
}
}
}
]
}
}
}
}
}
])