在检查MongoDB中的多个条件后更新深层嵌套数组中的元素

时间:2014-07-21 06:58:41

标签: mongodb

说,我有一个文档结构

[ {
  "name" : "in",
  "states" : [ {"name" : "up", 
                "cities" : [ {"name" : "dp", "places" : [ {"name" : "pvr"}, {"name" : "lpu"} ] }, 
                            {"name" : "mo", "places" : [ {"name" : "pvr"}, {"name" : "lpu"} ] } ]}, 
               {"name" : "tn", 
               "cities" : [ {"name" : "ab", "places" : [ {"name" : "pvr"}, {"name" : "lpu"} ] }, 
                            {"name" : "cd", "places" : [ {"name" : "pvr"}, {"name" : "lpu"} ] } ]} 
             ]
  },
  {
  "name" : "ik",
  "states" : [ {"name" : "up", 
                "cities" : [ {"name" : "dp", "places" : [ {"name" : "pvr"}, {"name" : "ont"} ] }, 
                            {"name" : "lo", "places" : [ {"name" : "zcv"}, {"name" : "bft"} ] } ]}, 
               {"name" : "kl", 
               "cities" : [ {"name" : "hp", "places" : [ {"name" : "bgh"}, {"name" : "vhi"} ] }, 
                            {"name" : "mp", "places" : [ {"name" : "hup"}, {"name" : "plm"} ] } ]} 
             ]
} ]

我想将"{"name" : "pvr"}"改为"{"name" : "cvr"}"" places"其中("name":"ik" and "states.name":"up" and "cities.name":"dp")。如何检查所有三个条件并更新?

1 个答案:

答案 0 :(得分:1)

由于您要更新的数组元素的位置未知,因此您需要获取匹配的状态和城市,迭代位置并在应用程序代码中设置新值。或者,如果经常进行这种更新,您可以对数据进行不同的建模,这样您就不会有太多级别的数组元素。