数组索引值匹配的Mongo更新查询

时间:2020-02-11 05:55:21

标签: mongodb mongodb-query

student集合如下所示。

[{
    "_id" : NumberLong(1),
    "studentId" : "70133",
    "subjects" : [ 
        "Mathematics", 
        "Biology and Zoology"
    ]
},
{
    "_id" : NumberLong(2),
    "studentId" : "70134",
    "subjects" : [ 
        "Mathematics", 
        "English"
    ]
},
{
    "_id" : NumberLong(3),
    "studentId" : "70135",
    "subjects" : [ 
        "English", 
        "Mathematics",
        "Chemistry"
    ]
}]);

我想编写一个查询来更新学生集合主题数组的值,如下所示:

  • 如果主题匹配English必须更新为 ENG
  • 如果主题匹配BiologyZoology必须更新为 BAZ
  • 如果主题匹配Mathematics必须更新为 MAT
  • 如果主题匹配Chemistry必须更新为 CHM

更新后的文档应如下所示。我该如何实现?

[{
    "_id" : NumberLong(1),
    "studentId" : "70133",
    "subjects" : [ 
        "MAT", 
        "BAZ"
    ]
},
{
    "_id" : NumberLong(2),
    "studentId" : "70134",
    "subjects" : [ 
        "MAT", 
        "ENG"
    ]
},
{
    "_id" : NumberLong(3),
    "studentId" : "70135",
    "subjects" : [ 
        "ENG", 
        "MAT",
        "CHM"
    ]
}]);

1 个答案:

答案 0 :(得分:0)

这必须通过多个更新来完成,例如:

db.collection.update(
    { "subjects" : { $in : [ "Mathematics" ] } },
    { $set: { "subjects.$" : "MAT" } },
    { multi: true }
)

有关更新多个文档的更多信息,请参见此页面

如果 multi 设置为true,则db.collection.update()方法将更新所有符合条件的文档。 multi 更新操作可能会与其他读/写操作交错。

https://docs.mongodb.com/master/reference/method/db.collection.update/index.html#multi-parameter

相关问题