简体   繁体   English

MongoDB Spring Data-按引用对象属性排序

[英]MongoDB Spring Data - Sort by Referenced object property

I search a lot trying to do what I want to do and can't find a solution. 我进行了大量搜索,试图做自己想做的事情,却找不到解决方案。 Can anyone help me? 谁能帮我?

I have two Mongo Collections: 我有两个Mongo Collections:

A. Post 一个帖子

{
    content: "...",
    user: {
        $ref: "user",
        $id: ObjectId(...)
    }
}

B. User B.用户

{
    name: "user name",
    age: 21
}

And I want to list all the posts sorted by User name, can I do it? 我想列出按用户名排序的所有帖子,可以吗?

I tried something like that: 我尝试过这样的事情:

Query query = new Query();
query.with(new Sort(new Sort.Order(Sort.Direction.ASC, "user.name")));
return mongoTemplate.find(query, Post.class);

But doesn't work, how can I do? 但是不行,我该怎么办?

MongoDB is only a document store by design, you can use it like a relational DB, if you have to something like this, either MongoDB在设计上仅是一个文档存储,您可以像关系数据库一样使用它,如果必须这样做,

  • MongoDB is not for you MongoDB不适合您
  • Or you need get both collections and join them manuell 或者您需要同时获得这两个收藏并加入manuell

With this schema you can't sort posts by user name in one atomic operation. 使用这种模式,您不能在一个原子操作中按用户名对帖子进行排序。 You have some choices: 您有一些选择:

  1. Use user names in field user and make sure that you have index on field name in users colection, so you can sort posts by user names in one operation and you will increase performance by using indexes. 在字段user中使用用户名,并确保在用户集合中对字段具有索引,因此可以在一个操作中按用户名对帖子进行排序,并且可以通过使用索引来提高性能。
  2. If you don't want to change schema, so try to use mongo aggregation framework. 如果您不想更改架构,请尝试使用mongo聚合框架。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM