在 MongoDB for Spring 中的@DBref列表项中查找/删除



在MongoDB for Spring中@DBRef查找和更新嵌套列表项的最佳方法是什么?

我有一个应用应用程序类:

@Document(collection = "applied_application")
public class AppliedApplication {
@Id
private String id;
@Field("program")
@DBRef
private List<Program> programList;
// getters and setters
}

程序类@DBRef

@Document(collection = "program")
public class Program {
@Id
private String id;
@Field("program_name")
private String programName;
// getters and setters
}

我正在寻找一种使用以下查询查找和更新嵌套列表项的方法:

用于通过应用的应用程序中ID查找程序对象的查询:

Query query = new Query();
query.addCriteria(Criteria.where("id").is(applicationId)
.and("program.$id").is(new ObjectId(programId)));
Program program = mongoTemplate.findOne(query, Program.class);

用于从应用的应用程序中删除列表项的查询:

Update update = new Update().pull("program", new BasicDBObject("program.$id", new ObjectId(programId)));
mongoTemplate.updateMulti(new Query(), update, AppliedApplication.class);

他们都没有工作,我完全不知道。

查找:

使用positional operator/$elemMatch在应用的应用程序中查找匹配的程序 DBRef。

使用$positional投影

Query query = new Query();
query.addCriteria(Criteria.where("id").is(new ObjectId(applicationId)).and("program.$id").is(new ObjectId(programId)));
query.fields().position("program", 1);
AppliedApplication application = mongoTemplate.findOne(query, AppliedApplication.class);
Program program = application.getProgramList().get(0);

使用$elemMatch投影

Query query = new Query();
query.addCriteria(Criteria.where("id").is(new ObjectId(applicationId)));
query.fields().elemMatch("program", Criteria.where("$id").is(new ObjectId(programId)));
AppliedApplication application = mongoTemplate.findOne(query, AppliedApplication.class);
Program program = application.getProgramList().get(0);

删除:

使用$pull从程序 DBref 列表中删除 DBRef。

Query query = Query.query(Criteria.where("$id").is(new ObjectId(programId)));
Update update = new Update().pull("program", query);
mongoTemplate.updateMulti(new Query(), update, AppliedApplication.class);

使用$push将新程序添加到列表中。

Query query = new Query();
query.addCriteria(Criteria.where("id").is(new ObjectId(applicationId)));
Update update = new Update().push("program", new DBRef("program", new ObjectId(programId));
mongoTemplate.updateMulti(query, update, AppliedApplication.class);

如果返回应用的应用程序,将运行第一个查询

Query query = new Query();
query.addCriteria(Criteria.where("id")
.is(new ObjectId(applicationId))
.and("program.$id")
.is(new ObjectId(programId)));
AppliedApplication  application = this.mongoOperations.findOne(query, AppliedApplication .class);

然后使用应用程序对象获取程序。

对于第二个查询,您需要更改 ,

Update update = new Update().pull("program", new BasicDBObject("$id", new ObjectId(programId)));
mongoTemplate.updateMulti(new Query(), update, AppliedApplication.class);

将 --> abc.$id 替换为 $id

最新更新