John Dek
John Dek

Reputation: 123

MongoDB query for objects in an array

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.

Upvotes: 2

Views: 105

Answers (1)

mickl
mickl

Reputation: 49945

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

Upvotes: 1

Related Questions