2

I have a collection that consists of objects like this:

{
    "name": "Event One",
    "user_id": "1"
    "rsvp": [
        {"id": "1","name":"John Doe","industry":"Software"},
        {"id": "2","name":"John Doe II","industry":"Software"},
    ]

}

I am trying to query all events that a user has rsvp too and that he did not create. Then match the rsvp with the industry the are in. Is it possible to query in mongoDB and have it returned like this:

[
     {"id": "1","name":"John Doe"},
     {"id": "2","name":"John Doe II"},
]

The query I have is below:

events.find({"$and":[{"rsvp.contact.indusrty":{"$in":["Software","Information Systems"]}},{"user_id":{"$ne":"5d335704802df000076bad97"}}]},{"projection":{"rsvp.contact.name":true},"typeMap":{"root":"array","document":"array"}})

I am new to MONGODB and can't seem to find anything that is helping me figure this out.

1 Answer 1

1

You need $match to define filtering criteria, $unwind to get single document per rsvp and $replaceRoot to promote rsvp to root model:

db.events.aggregate([
    {
        $match: {
            "$and":[
                {
                    "rsvp.industry":{
                        "$in":["Software","Information Systems"]
                    }
                },
                {   "user_id":{"$ne":"5d335704802df000076bad97"}}
            ]
        }
    },
    {
        $unwind: "$rsvp"
    },
    {
        $replaceRoot: {
            newRoot: "$rsvp"
        }
    },
    {
        $project: {
            industry: 0
        }
    }
])

Mongo Playground

Sign up to request clarification or add additional context in comments.

6 Comments

If I had a user_ id in each of the rsvp records to filter out the current users rsvp I would get add{ "rsvp.user_id":{"$ne":"5d335704802df000076bad97"}} after the other user_id check?
Yes, that makes sense. If you're still experiencing some difficulties please create mongo playground and I will try to take a look
Need to select all events that the logged in user has rsvp to or has created. then return the rsvp array of objects like it has
If you expect to get single document you should re-arrange your pipeline and run $unwind before $match so that filtering criteria will be applied separately to both rsvp items: mongoplayground.net/p/hVAKv_6FHLB
So if this query will get all rsvp that you match industries with including when you created the event?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.