【问题标题】:Convert mongo shell query to QueryDBObject and execute using spring mongotemplate将 mongo shell 查询转换为 QueryDBObject 并使用 spring mongotemplate 执行
【发布时间】:2015-08-22 21:27:35
【问题描述】:

以下是我能够在我的 mongo shell 上正确执行的查询。

db.students.update({ _id : 139 }, {$pull : { scores: {type :'homework' }}})

我需要使用 Java 程序/Mongo Spring 模板执行相同的操作。 有人可以帮我看看怎么做吗?

【问题讨论】:

  • 有人知道如何使用 spring mongo 模板吗

标签: java mongodb spring-mongo


【解决方案1】:

您的查询可能与此类似:

UpdateResult updateResult = collection.updateOne(eq("_id", 123),
      new Document("$pull", new Document("scores",
          new Document("type", "homework"))
      )
);

Here您已经获得了整个界面和具体 updateOne 的文档。

您还需要与数据库建立连接,因此您可能需要关注this quick tour 来完成它。

编辑

为了对 spring mongo 做同样的事情,你可以这样做(正如 the docs 中所记录的那样):

import static org.springframework.data.mongodb.core.query.Criteria.where;
import static org.springframework.data.mongodb.core.query.Query;
import static org.springframework.data.mongodb.core.query.Update;

...

WriteResult wr = mongoTemplate.updateFirst(new Query(where("accounts.accountType").is(Account.Type.SAVINGS)),
  new Update().pull("students.$.scores", new Document("type", "homework")), Account.class);

PS:这个答案可能不会按原样工作,这只是一个示例,如果您需要更好的帮助,请提供更大的 sn-ps 代码。

【讨论】:

  • - { "_id" : 15,"name" : "Tambra Mercure","scores" : [{"type" : "exam","score" : 69.1565022533158},{"type" :“测验”,“分数”:3.311794422000724},{“类型”:“家庭作业”,“分数”:45.03178973642521},{“类型”:“家庭作业”,“分数”:42.19409476640781}]} ----- - 这是我需要删除文档数组中的作业的 json。这是我正在使用的查询 - mongoOperation.updateFirst(new Query(where("_id").is(15)), new Update().pull("students.$.scores", "homework"), obj.班级); @VdeVatman
  • 嗨,我得到了这个工作 - BasicDBObject ob = new BasicDBObject("_id", Double.valueOf(g.getId())); BasicDBObject ob2 = new BasicDBObject("$pull",new BasicDBObject("scores", new BasicDBObject("type","homework").append("score", dob))); collection.update(ob, ob2)
  • 很高兴听到,尝试回答你自己并将你自己的答案自动标记为解决方案。
猜你喜欢
  • 1970-01-01
  • 2020-05-07
  • 1970-01-01
  • 2022-01-17
  • 2019-10-14
  • 1970-01-01
  • 2019-12-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多