V
V
vostotskiy2018-06-19 14:27:53
JavaScript
vostotskiy, 2018-06-19 14:27:53

How to filter lookup aggregation results in MongoDB?

Good day. There is the following task.
There is an Event entity that has its own description, which has its own list of organizers in the form of an array of links and a list of workshops (the Workshop entity).

const EventSchema = new Schema(
  {
    title: {type: String, default:'', required: true},
    description: {type: String, default:''},
    startDate: {type: Date, default: Date.now, required: true},
    founders: [{ type: Schema.Types.ObjectId, ref: 'User' }],
    workshops: [{ type: Schema.Types.ObjectId, ref: 'Workshop' }],
  });

The two entities are stored as separate collections.
Approximate structure of the Workshop entity
const WorkshopSchema = new Schema(
  {
    title: {type: String, default:'', required: true},
    description: {type: String, default:''},
    event:{ type: Schema.Types.ObjectId, ref: 'Event' },
    actors: [{ type: Schema.Types.ObjectId, ref: 'User' }],
  });

One event (event) can have several workshops (master classes).
To display the event parameters on the workshop page, a populate request is made on the workshops field, the workshop
entity also has an Event field, on which populate is done to display the Event parameters on the page of a specific workshop.
What is the task - you need to pull out all the workshops related to a particular user, namely: he can be among the actors of a particular workshop or in the list of founders of the Event (then all the workshops associated with the event need to be pulled out)
There is an assumption that you need initially make the correct aggregation: initially attach workshops to their parent events with a lookup, and then filter by the OR condition (the presence of the user id in Event.founders and Workshop.actors)
Directly lookup looks like this
db.getCollection('workshops').aggregate([
   {
     $lookup:
       {
         from: "events',
         localField: "event",
         foreignField: "_id",
         as: "events"
       }
  }
])

Tell me, please, how to do the subsequent OR filtering by Event.founders and Workshop.actors by the ID of a specific user (presence in the ID array) or how to build the request logic in another way.
Thanks in advance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Philipp, 2018-06-19
@vostotskiy

Add $match after $lookup using the $or operator. You can also access fields.
Something like that:

$lookup...,
$or: [
  {actors: USER_OBJECT},
  {'events.founders': USER_OBJECT}
]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question