vapor-community / mongo-driver

MongoDB driver for Fluent
28 stars 26 forks source link

Support unions / aggregations #13

Closed tanner0101 closed 7 years ago

tanner0101 commented 8 years ago

Unions are currently unsupported making siblings relations impossible in Fluent.

Would need to go here:

https://github.com/vapor/mongo-driver/blob/master/Sources/Query%2BMongoKitten.swift#L12

Something like:

if query.unions.count > 0 {
    // do mongo magic
}
tanner0101 commented 8 years ago

Also putting a nicer error for: https://github.com/vapor/mongo-driver/blob/master/Sources/Filter%2BMongoKitten.swift#L55 would be nice.

Joannis commented 8 years ago

@tannernelson this can be solved another way too. So if you store the ObjectId (or other ID that you're using) in the Document of the model and your model knows what collection you're referencing to. Let's say the PrivateMessage object referencing to User object. This Model (privatemessage) knows that it's referencing a User model, thus it can be resolved that way. It costs an extra query. Alternatively you can store a https://docs.mongodb.com/manual/reference/database-references/#dbrefs and resolve that automatically. I've already added support for DBRefs in the upcoming MongoKitten, but it's not difficult at all to implement

tanner0101 commented 7 years ago
{
   $lookup:
     {
       from: <collection to join>,
       localField: <field from the input documents>,
       foreignField: <field from the documents of the "from" collection>,
       as: <output array field>
     }
}

Looks like this is how to do it.

http://stackoverflow.com/questions/2350495/how-do-i-perform-the-sql-join-equivalent-in-mongodb

let pipeline: AggregationPipeline = [
    .lookup(fromCollection: String, localField: String, foreignField: String, as: String)
]
Joannis commented 7 years ago

Yup. It's already supported in MongoKitten. Please note that this is a feature requiring MongoDB 3.2 or above. MongoKitten will throw an error if this is used on lower versions.