简体   繁体   中英

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. Each child document has a parentId field too.

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).

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. Parent has a childId, just not 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.

Any ideas?

One way to solve this is to use the herteby:denormalize package to denormalize you database with something like this :

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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