【问题标题】:Mongo Update Query on Array Index value matchingMongo更新查询数组索引值匹配
【发布时间】:2020-02-11 05:55:21
【问题描述】:

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
  • 如果主题匹配 Biology 和 Zoology 必须更新为 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"
    ]
}]);

【问题讨论】:

  • 答案取决于您使用的是哪个版本的 mongo,如果您正在寻找条件更新,那么它们只是 supported from v4.2。否则,您可能需要编写脚本来进行更新。

标签: mongodb mongodb-query


【解决方案1】:

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

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

【讨论】:

  • 谢谢凯文,它适用于多个更新查询。"subject.$" 这里 $ 将在查询的条件部分获取该索引?
  • 不客气! “subjects.$”被称为位置 $ 运算符,并充当与查询文档匹配的第一个元素的占位符。
猜你喜欢
  • 2021-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-25
  • 1970-01-01
  • 1970-01-01
  • 2016-05-05
  • 2017-02-23
相关资源
最近更新 更多