简体   繁体   English

将mongo shell查询转换为QueryDBObject并使用spring mongotemplate执行

[英]Convert mongo shell query to QueryDBObject and execute using spring mongotemplate

Below is the query which i am able to execute on my mongo shell properly. 以下是我能够在mongo shell上正确执行的查询。

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

I need to execute the same thing using a Java program / Mongo Spring Template. 我需要使用Java程序/ Mongo Spring模板执行相同的操作。 Could somebody help show me how to do this? 有人可以帮我看看如何做吗?

Your query might be similar to this: 您的查询可能与此类似:

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

Here you've got the documentation of the entire interface and of updateOne in specific. 在这里,您可以获得整个界面以及特定于updateOne的文档。

You also need a connection with the database, so you might want to follow this quick tour to get it done. 您还需要与数据库建立连接,因此您可能需要按照此快速导览完成操作。

EDIT 编辑

For doing the same with spring mongo, you can do (as it is documented in the docs ) something like this: 对于spring mongo,您可以执行以下操作(如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: This answer probably won't work as is, it's just an example, if you want better help give larger snippets of code. PS:如果您想更好地帮助提供更大的代码段,则此答案可能无法按原样工作,这只是一个示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM