java—SpringMongo中有没有内置的函数可以用来从两个具有一对一关系的不同文档中提取数据?

ndasle7k  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(403)

我只是想在spring中使用mongo模板从mongodb中具有onetoone关系的两个不同文档中提取数据。
我有两个文档“rosters”(属于用户的嵌入文档)和“unread”都由“ucid”标识,这是“unique conversation identifier”的缩写。我想在ucid的基础上执行内部连接操作并提取数据。有很多例子表明,查找和聚合用于onetomany关系,而不用于onettoone。
以下是课程

  1. **User**
  2. class User
  3. {
  4. private List<Roster> rosterList;
  5. }
  6. **Roster**
  7. public class Roster extends Parent
  8. {
  9. @Id
  10. private ObjectId _id;
  11. @Indexed
  12. private String author;
  13. @Unique
  14. private String ucid;
  15. }
  16. **Unread**
  17. public class
  18. {
  19. @Id
  20. @Indexed(unique=true) //todo: create index on mongo side as well
  21. private String ucid;
  22. private Map<String,Long> memberAndCount;
  23. }
  24. ----------------------------------------------------
  25. Sample Data:
  26. USER (roster)
  27. {user:{id:1001, username: dilag,roster:
  28. [{
  29. ucid:r0s122,name:sam}
  30. },{
  31. ucid:r0s123,name:ram}
  32. },{
  33. ucid:r0s124,name:rat}
  34. }]}
  35. UNREAD
  36. {
  37. ucid:r0s122,usernameAndCount:[{username:dilag,count:100},{username:ramg,count:20}],
  38. ucid:r0s123,usernameAndCount:[{username:dilag,count:100},{username:ramg,count:20}]
  39. }
  40. Desired Output
  41. {
  42. ucid:r0s122, name :sam,usernameAndCount:[{username:dilag,count:100},{username:ramg,count:20}],
  43. ucid:r0s123,name:ram,usernameAndCount:[{username:dilag,count:100},{username:ramg,count:20}]
  44. }
yiytaume

yiytaume1#

下面的spring代码没有经过测试,但它是基于mongo平台编写的。
基本上,您需要知道如何使用 $lookup . 这里我使用了连接不相关的子查询

  1. public List<Object> test() {
  2. Aggregation aggregation = Aggregation.newAggregation(
  3. l-> new Document("$lookup",
  4. new Document("from","user")
  5. .append("let", new Document("uid","$uicd"))
  6. .append("pipeline",
  7. Arrays.asList(
  8. new Document("$unwind", "$user.roster"),
  9. new Document("$match",
  10. new Document("$expr",
  11. new Document("$eq",Arrays.asList("$user.roster.ucid","$$uid"))
  12. )
  13. )
  14. )
  15. ).append("as","users")
  16. ),
  17. a-> new Document("$addFields",
  18. new Document("name",
  19. new Document("$ifNull",
  20. Arrays.asList(
  21. new Document("$arrayElemAt", Arrays.asList("$users.user.roster.name",0))
  22. ,
  23. ""
  24. )
  25. )
  26. )
  27. )
  28. ).withOptions(AggregationOptions.builder().allowDiskUse(Boolean.TRUE).build());
  29. return mongoTemplate.aggregate(aggregation, mongoTemplate.getCollectionName(Unread.class), Object.class).getMappedResults();
  30. }

阅读本文,了解在mongo-spring数据不提供任何操作的情况下如何进行聚合的技巧 new Document() .

展开查看全部

相关问题