8

Spring Data 和 MongoDB 的第一次实验很棒。现在我有以下结构(简化):

public class Letter {
  @Id
  private String id;
  private List<Section> sections;
}

public class Section {
  private String id;
  private String content;
}

加载和保存整个 Letter 对象/文档就像一个魅力。(我使用 ObjectId 为 Section.id 字段生成唯一的 ID。)

Letter letter1 = mongoTemplate.findById(id, Letter.class)
mongoTemplate.insert(letter2);
mongoTemplate.save(letter3);

由于文档很大(200K),有时应用程序只需要子部分:是否有可能查询子文档(部分),修改并保存它?我想实现一个像

Section s = findLetterSection(letterId, sectionId);
s.setText("blubb");
replaceLetterSection(letterId, sectionId, s);

当然还有如下方法:

addLetterSection(letterId, s); // add after last section
insertLetterSection(letterId, sectionId, s); // insert before given section
deleteLetterSection(letterId, sectionId); // delete given section

我看到最后三种方法有些“奇怪”,即加载整个文档、修改集合并再次保存它,从面向对象的角度来看可能是更好的方法;但是第一个用例(“导航”到子文档/子对象并在该对象的范围内工作)似乎很自然。

我认为MongoDB可以更新子文档,但是SpringData可以用于对象映射吗?感谢您的任何指示。

4

3 回答 3

18

我想出了以下仅切片和加载一个子对象的方法。好像没问题?我知道并发修改的问题。

Query query1 = Query.query(Criteria.where("_id").is(instance));
query1.fields().include("sections._id");
LetterInstance letter1 = mongoTemplate.findOne(query1, LetterInstance.class); 
LetterSection emptySection = letter1.findSectionById(sectionId);
int index = letter1.getSections().indexOf(emptySection);

Query query2 = Query.query(Criteria.where("_id").is(instance));
query2.fields().include("sections").slice("sections", index, 1);
LetterInstance letter2 = mongoTemplate.findOne(query2, LetterInstance.class);
LetterSection section = letter2.getSections().get(0);

这是加载所有部分但省略其他(大)字段的替代解决方案。

Query query = Query.query(Criteria.where("_id").is(instance));
query.fields().include("sections");
LetterInstance letter = mongoTemplate.findOne(query, LetterInstance.class); 
LetterSection section = letter.findSectionById(sectionId);

这是我用于仅存储单个集合元素的代码:

MongoConverter converter = mongoTemplate.getConverter();
DBObject newSectionRec = (DBObject)converter.convertToMongoType(newSection);

Query query = Query.query(Criteria.where("_id").is(instance).and("sections._id").is(new ObjectId(newSection.getSectionId())));
Update update = new Update().set("sections.$", newSectionRec);
mongoTemplate.updateFirst(query, update, LetterInstance.class);

很高兴看到 Spring Data 如何与 MongoDB 的“部分结果”一起使用。

任何意见高度赞赏!

于 2012-08-21T12:19:53.853 回答
2

I think Matthias Wuttke's answer is great, for anyone looking for a generic version of his answer see code below:

@Service
public class MongoUtils {

  @Autowired
  private MongoTemplate mongo;

  public <D, N extends Domain> N findNestedDocument(Class<D> docClass, String collectionName, UUID outerId, UUID innerId, 
    Function<D, List<N>> collectionGetter) {
    // get index of subdocument in array
    Query query = new Query(Criteria.where("_id").is(outerId).and(collectionName + "._id").is(innerId));
    query.fields().include(collectionName + "._id");
    D obj = mongo.findOne(query, docClass);
    if (obj == null) {
      return null;
    }
    List<UUID> itemIds = collectionGetter.apply(obj).stream().map(N::getId).collect(Collectors.toList());
    int index = itemIds.indexOf(innerId);
    if (index == -1) {
      return null;
    }

    // retrieve subdocument at index using slice operator
    Query query2 = new Query(Criteria.where("_id").is(outerId).and(collectionName + "._id").is(innerId));
    query2.fields().include(collectionName).slice(collectionName, index, 1);
    D obj2 = mongo.findOne(query2, docClass);
    if (obj2 == null) {
      return null;
    }
    return collectionGetter.apply(obj2).get(0);
  }

  public void removeNestedDocument(UUID outerId, UUID innerId, String collectionName, Class<?> outerClass) {
    Update update = new Update();
    update.pull(collectionName, new Query(Criteria.where("_id").is(innerId)));
    mongo.updateFirst(new Query(Criteria.where("_id").is(outerId)), update, outerClass);
  }
}

This could for example be called using

mongoUtils.findNestedDocument(Shop.class, "items", shopId, itemId, Shop::getItems);
mongoUtils.removeNestedDocument(shopId, itemId, "items", Shop.class);

The Domain interface looks like this:

public interface Domain {

  UUID getId();
}

Notice: If the nested document's constructor contains elements with primitive datatype, it is important for the nested document to have a default (empty) constructor, which may be protected, in order for the class to be instantiatable with null arguments.

于 2018-04-26T10:48:09.140 回答
0

解决方案

这就是我对这个问题的解决方案:

对象应该更新

@Getter
@Setter
@Document(collection = "projectchild")
public class ProjectChild {
  @Id
  private String _id;

  private String name;

  private String code;

  @Field("desc")
  private String description;

  private String startDate;

  private String endDate;

  @Field("cost")
  private long estimatedCost;

  private List<String> countryList;

  private List<Task> tasks;

  @Version
  private Long version;
}

编码解决方案

  public Mono<ProjectChild> UpdateCritTemplChild(
       String id, String idch, String ownername) {

    Query query = new Query();
    query.addCriteria(Criteria.where("_id")
                              .is(id)); // find the parent
    query.addCriteria(Criteria.where("tasks._id")
                              .is(idch)); // find the child which will be changed

    Update update = new Update();
    update.set("tasks.$.ownername", ownername); // change the field inside the child that must be updated

    return template
         // findAndModify:
         // Find/modify/get the "new object" from a single operation.
         .findAndModify(
              query, update,
              new FindAndModifyOptions().returnNew(true), ProjectChild.class
                       )
         ;

  }
于 2021-12-23T16:22:34.213 回答