下面是我能够在我的 mongo shell 上正确执行的查询。
db.students.update({ _id : 139 }, {$pull : { scores: {type :'homework' }}})
我需要使用 Java 程序/Mongo Spring 模板执行相同的操作。有人可以帮我看看怎么做吗?
下面是我能够在我的 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 做同样的事情,你可以做这样的事情(如文档中所述):
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:这个答案可能不会按原样工作,它只是一个例子,如果你想要更好的帮助提供更大的代码片段。