【问题标题】:How to update sub documents value of different documents based on different filter in mongoDB?如何根据mongoDB中的不同过滤器更新不同文档的子文档值?
【发布时间】:2018-08-17 22:18:01
【问题描述】:

如何使用单个脚本根据mongoDB中的不同过滤器更新不同文档的子文档值

 {
"_id" : ObjectId("5aa2516c732e89b875rtg"),
"username" : "user1",
"password" : "password1",
"level0" : {
    "level1" : {
        "value1" : 2,
        "value2" : 2
     }
   }
 },
 {
 "_id" : ObjectId("5aa2516c732e89b8hy5"),
  "username" : "user2",
  "password" : "password2",
  "level0" : {
    "level1" : {
        "differntvalue1" : 2,
        "differntvalue2" : 2
     }
   }
 }

这里我只想通过运行单个脚本来更新文档(在子文档中添加新值),结果应该如下所示

{
 "_id" : ObjectId("5aa2516c732e89b875rtg"),
  "username" : "user1",
  "password" : "password1",
   "level0" : {
    "level1" : {
       "value1" : 2,
       "value2" : 2,
       "value3" : 2
   }
 }
},
  {
  "_id" : ObjectId("5aa2516c732e89b8hy5"),
   "username" : "user2",
   "password" : "password2",
   "level0" : {
     "level1" : {
        "differntvalue1" : 2,
        "differntvalue2" : 2,
        "differntvalue3" : 2
   }
 }
}

MongoDB: Upserting and Sub documents - 这个答案很有帮助,但不允许同时对不同文档进行不同更新。

【问题讨论】:

  • 您尝试过使用 parent.$.child 吗?
  • 是的。这已经尝试过了,对于单个文档更新它工作正常。但不适用于多个文档。为什么 $ 符号不接受,我尝试作为 parent.child 并且哪个有效
  • 你能显示当前的代码吗?有什么不同的过滤器?搜索条件是什么?
  • @Veeram - 请为我当前的代码找到以下答案,如果您有任何建议,请告诉我
  • 不认为这是可能的。你只需要做两个查询。您只能在一个查询中为不同的过滤器更新具有相同值的多个文档。

标签: mongodb mongodb-query spring-data


【解决方案1】:

我刚刚尝试对每个文档使用不同的更新命令。有没有办法与单个更新一起完成?

 db.mycollection.update(
   {"username": "user1"},
   { 
   $set :{
     "level0.level1.value3" : 2
     }
    });
 db.mycollection.update(
  {"username": "user2"},
  { 
   $set :{
    "level0.level1.differntvalue3" : 2
    }
  });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多