Search code examples
databasemongodbalgorithmmongodb-queryrdbms

Performing Relational Query on Mongodb


I have two collections. One named events and another named applications. Applications contains user application data for paticular event. I want to find those events in which user has not applied.

NOTE:
1. eventId field in applications is DBRef to events collection.
2. userId field in applications is DBRef to users collection.
3. A user can only apply single time to an event.

Please help me out. Thanks in advance.

Events:

[
    {
        "_id" : ObjectId("5d07c45fabb5c771f8a81228"),
        "fee" : 400
    },
    {
        "_id" : ObjectId("5d07c461abb5c771f8a81229"),
        "fee" : 500
    },
    {
        "_id" : ObjectId("5d07c463abb5c771f8a8122a"),
        "fee" : 700
    },
    {
        "_id" : ObjectId("5d07c466abb5c771f8a8122b"),
        "fee" : 800
    }
]

Applications:

[
    {
        "_id" : ObjectId("5d07c4e8abb5c771f8a8122c"),
        "eventId" : ObjectId("5d07c45fabb5c771f8a81228"),
        "userId" : ObjectId("5d07c45fabb5c772f8a81978"),
        "text" : "I am interested"
    }
]


Solution

  • Stage 1: $lookup - Used to join events and applications collections

    Stage 2: $match - Filter the events that don't have any user application

    [
        {
            '$lookup': {
                'from': 'applications', 
                'localField': '_id', 
                'foreignField': 'eventId', 
                'as': 'eventsApps'
            }
        }, {
            '$match': {
                '$expr': {
                    '$lte': [
                        {
                            '$size': '$eventsApps'
                        }, 0
                    ]
                }
            }
        }
    ]