[英]Convert mongo shell query to QueryDBObject and execute using spring mongotemplate
以下是我能夠在mongo shell上正確執行的查詢。
db.students.update({ _id : 139 }, {$pull : { scores: {type :'homework' }}})
我需要使用Java程序/ Mongo Spring模板執行相同的操作。 有人可以幫我看看如何做嗎?
您的查詢可能與此類似:
UpdateResult updateResult = collection.updateOne(eq("_id", 123),
new Document("$pull", new Document("scores",
new Document("type", "homework"))
)
);
在這里,您可以獲得整個界面以及特定於updateOne的文檔。
您還需要與數據庫建立連接,因此您可能需要按照此快速導覽完成操作。
編輯
對於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:如果您想更好地幫助提供更大的代碼段,則此答案可能無法按原樣工作,這只是一個示例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.