mongo db 对父集合和子集合字段进行排序
好的,我有两个集合,父集合和子集合。 父集合可以有多个子文档。
现在我希望能够按 ChildCollection 文档自己的字段及其父级的字段对它进行排序。这可能吗?是的,我可以把它放在一个大集合中,但这会造成很多冗余。这将适用于数百万条记录,因此可以在服务器上完成的操作越多越好。
ParentCollection
_id : "parentid1"
field1 : "val1"
field2 : "val2"
fieldx.......
ChildCollection
_id : "childid1"
_parentid: "parentid1"
field1 : "val3"
field2 : "val4"
fieldx.........
Ok I have two Collections, Parent and Child.
A parent collection can have multiple Child documents.
Now I'd like to be able to to sort ChildCollection documents by it's own fields as well as the fields of it's parent. Is this possible? Yes, I could put it in one big Collection but it will be a lot of redundancies. This would be for millions of records so the more that can be done on the server the better.
ParentCollection
_id : "parentid1"
field1 : "val1"
field2 : "val2"
fieldx.......
ChildCollection
_id : "childid1"
_parentid: "parentid1"
field1 : "val3"
field2 : "val4"
fieldx.........
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
要在父集合字段上对子集合进行排序,您应该将要排序的父字段放入每个子集合中。没有其他方法可以做到这一点。当您更新父文档时,您将需要更新所有子文档中的这些字段。 Mongodb 喜欢非规范化,所以不用关心这个。另外,为了提高父字段更新的速度,您可以使子更新异步。
To sort child collection on parent collection fields you should put parent fields on which you want sort into the each child. There is no another way to do this. And you will need update these fields in all child's when you update parent document. Mongodb love denormalization, so don't care to this. Also to increase speed of parent fields update you can make child updates async.
有一个解决方法。
通过使用
$sort
我能够对子集合进行排序。我将相同的代码返回到 JavaList
并使用Collections.sort(List);
实现父集合的排序,瞧!There is a work around.
By using
$sort
I was able to sort the child collection. I returned the same code to a JavaList
and implemented sorting of parent collection there usingCollections.sort(List<T>);
and VOILA!