简体   繁体   English

Mongodb 按另一个数组的顺序排序

[英]Mongodb sort by order of another array

I have a couple related collections, let's call them parent and child.我有几个相关的集合,让我们称它们为父子。

My problem is that I'm trying to sort parent documents by a child.name field.我的问题是我试图通过 child.name 字段对父文档进行排序。 Each child document has a parentId field too.每个子文档也有一个 parentId 字段。

I created an array of projections that's a mapping of child _ids to names and that's in the sort order I want (alphabetically by name).我创建了一个投影数组,它是子 _id 到名称的映射,并且按照我想要的排序顺序(按名称的字母顺序)。

ie IE

Child documents子文件

 [
        {_id: "GiXtSJqg22aYf6h7r", name: "Allen"}
        {_id: "rRCiqcEAsDaDeJYL3", name: "Bob"}
        {_id: "bP2kKbsofyqKjp9Zq", name: "Chris"}
        {_id: "8so7KNeTwQGbLvwxo", name: "Darien"}
        {_id: "XZ7kMDSjae82ddi7p", name: "Edgar"}
        {_id: "k5j8LWTbWEStNhK5p", name: "Sally"}
]

I then wanna have some Parent documents returned sorted by the child.name as seen above.然后我想要返回一些按 child.name 排序的父文档,如上所示。 Parent has a childId, just not child.Name.父母有一个 childId,只是没有 child.Name。 So I figure I should be able to figure this out with a mapping.所以我想我应该能够通过映射来解决这个问题。

Is there anyway to do something like the following..反正有没有做类似以下的事情..

Parents.find({}, { sort: {childId: ORDER_OF_MAPPING._id} }

So the sort order is " ascending based on the order of the mapping ".所以排序顺序是“根据映射顺序升序”。

I'm looking to do this without an aggregation as I'm using a Meteor Publish method to return my cursor.我希望在没有聚合的情况下执行此操作,因为我正在使用 Meteor Publish 方法返回我的光标。

Any ideas?有任何想法吗?

One way to solve this is to use the herteby:denormalize package to denormalize you database with something like this :解决此问题的一种方法是使用herteby:denormalize包通过以下方式对数据库进行非规范化

ParentCollection.cache({
  type:'one',
  collection: ChildCollection,
  fields:['name'],
  referenceField:'childId',
  cacheField:'child'
})

Then (after running the data migration needed to update your database with denormalized fields) you will be able to sort ParentCollection documents on the child.name key.然后(在运行使用非规范化字段更新数据库所需的数据迁移之后)您将能够在child.name键上对 ParentCollection 文档进行排序。

Denormalization will impact the write operations that will cost more (each time you edit the child, the package will also modify the parent), but then the reads can be optimized (less queries to achieve the same result).非规范化会影响写入操作,这将花费更多(每次编辑子项时,包也会修改父项),但随后可以优化读取(更少的查询以获得相同的结果)。

This methods assumes one Parent has only one Child (ie it's a one-to-one relation between the tables), which seems consistent with the sorting you are describing in your question这种方法假设一个父级只有一个子级(即表之间的一对一关系),这似乎与您在问题中描述的排序一致

Another very powerful package that can help you is cultofcoders:grapher另一个可以帮助你的非常强大的包是cultofcoders:grapher

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

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