【问题标题】:MongoDB update element of nested arrayMongoDB更新嵌套数组的元素
【发布时间】:2016-05-10 14:23:54
【问题描述】:

我有一个名为 Firma 的 mongo 集合,它的文档结构之一如下:

 {
    "_id" : ObjectId("5729af099b3ebf1d0ca7ff05"),
    "musteriler" : [ 
        {
            "_id" : "de0bf813-b707-4a8d-afc2-9752e05c3aa5",
            "yetkiliListesi" : [ 
                {
                    "_id" : "a5e487fa-2034-4817-94f2-3bd837b76284",
                    "ad" : "Burak",
                    "soyad" : "Duman 1",
                    "cepTel" : "3333333333333",
                    "mail" : "asdf@asdf.com"
                }, 
                {
                    "_class" : "com.bisoft.entity.MusteriYetkili",
                    "_id" : "bc4b537d-522a-4c9a-9f67-8ca243e18f46",
                    "ad" : "Ridvan",
                    "soyad" : "ENİŞ",
                    "cepTel" : "222222222222",
                    "mail" : "asdf@asdf.com"
                }
            ]
        }
    ],
    "defaultTimezone" : "Europe/Istanbul"
    }

在上面的 json 中,我需要更新第二个数组(yetkiliListesi)的元素,其中 _id = "a5e487fa-2034-4817-94f2-3bd837b76284"

由于我使用的是 java 应用程序(使用 mongo java 驱动程序和 spring boot MongoTemplate)来访问它并执行此查询:

 mongoTemplate.updateFirst(Query.query(Criteria.where("_id").is("5729af099b3ebf1d0ca7ff05").and("musteriler.yetkiliListesi._id").is("a5e487fa-2034-4817-94f2-3bd837b76284")), 
            new Update().set("musteriler.yetkiliListesi.$", yetkiliDBO), Firma.class);

在上述查询中,yetkiliDBO 是一个 BasicDBObject 及其内容:

yetkiliDBO = { 
    '_class': 'com.bisoft.entity.MusteriYetkili', 
    '_id': "a5e487fa-2034-4817-94f2-3bd837b76284", 
    'ad': 'wer', 
    'soyad': 'xyz', 
    'cepTel': "222222222222",
     mail: "asdf@asdf.com" 
}

执行查询时出现错误

com.mongodb.WriteConcernException: { "serverUsed" : "192.168.2.250:27017" , "ok" : 1 , "n" : 0 , "updatedExisting" : false , "err" : "cannot use the part (musteriler of musteriler.yetkiliListesi.0) to traverse the element 

我需要做什么?

【问题讨论】:

    标签: java spring mongodb spring-boot spring-data


    【解决方案1】:

    遍历嵌套数组时不能使用“$”占位符。

    位置 $ 运算符不能用于遍历多个数组的查询,例如遍历嵌套在其他数组中的数组的查询,因为 $ 占位符的替换是单个值

    source

    我建议将您的数据重组为单独的、嵌套较少的集合。

    【讨论】:

    • 您可以更新整个 'yetkiliListesi' 数组:new Update().set("musteriler.$.yetkiliListesi", List<yetkiliDBO>),但我强烈建议您重组数据。
    猜你喜欢
    • 2022-01-22
    • 2020-03-16
    • 2020-09-15
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 2018-10-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多