首先,下面是mongodb的文档类,
@Getter
@Setter
@Document(collection="Posts") // The name of collection is "Posts"
public class Post {
@Id
private String _id;
@Indexed(unique = true)
private Long id;
@Field
private String title;
@Field
private String body;
@Field
private Date createdDate;
@DBRef
private User user;
@DBRef
private Collection<Tag> tags;
}
我制作了简单的 mongorepository 界面
public interface PostMongoRepository extends MongoRepository<Post, Long> {
}
但是我在将初始json数据加载到服务层的mongodb时遇到了麻烦,
try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "EUC-KR"))) {
String line;
StringBuffer strBuffer = new StringBuffer();
while ((line = br.readLine()) != null) {
strBuffer.append(line+ "\n");
}
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
TypeReference<List<Post>> typeReference = new TypeReference<List<Post>>(){};
Collection<Post> posts = objectMapper.readValue(strBuffer.toString(), typeReference);
// I am stuck on this line
if(postMongoRepository.FIND_THE_COLLECTION_TITLE) {
for(Post post : posts) {
postMongoRepository.save(post);
}
}
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
我尝试确认是否生成了“帖子”集合。但我不知道如何通过 mongorepository 接口找到现有的集合。我尝试使用 @Query 注释,但它仅限于键值,而不是集合。
我想了解如何使用 mongorepository 接口查找现有的 mongodb 数据库集合。