【问题标题】:Update array of a document by using replaceOne or replace in MongoDB?在 MongoDB 中使用 replaceOne 或 replace 更新文档数组?
【发布时间】:2017-05-31 06:55:42
【问题描述】:

我们可以在 MongoDB 中使用 replaceOne 或 replace 来更新文档数组吗?

db.employeeDetails.find().pretty()
{
    "_id"  : ObjectId("587c99a3cc61ca283575bf75"),
    "eid"  : 1882031,
    "addr" : [
                {
                        "fNo"   :  8,
                        "bName" : "Abc Apts"    
                        "town"  : "My Town"
                }


             ]
}

现在我想使用replace 或replaceOne 更新城镇。我不想阅读文档然后更新。

【问题讨论】:

  • 您是否使用 Spring DAO 实现通过 Java 与 Mongo 进行交互?
  • 不是 SpringDAO 我正在使用 Mongo 驱动程序
  • 输入是什么?你怎么知道在哪个文件中更新哪个城镇?
  • 我想更新employeeDetails,你可以看到有一个地址数组,我存储了Flat No.、Build Name 和Town,在我的收藏中可能有超过1000 名不同eid 的员工.现在我正在读取计数,然后检查计数是否大于 0,然后更新其他插入。但是现在我想避免阅读我想匹配模式,如果匹配则直接更新 else 插入。

标签: java mongodb


【解决方案1】:

您可以像这样使用更新 操作

 db.test.update(
{ _id: ObjectId("57f4997e551422c9cc5eeff2") },
   { $set: 
      {"test.0": { "scores" :89, "name" : "halim" }
      }
   }
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-08
    • 1970-01-01
    • 2016-11-04
    • 2016-11-23
    • 1970-01-01
    • 2015-01-07
    • 2016-12-31
    • 1970-01-01
    相关资源
    最近更新 更多