Suppose I have this MongoDB document:
{
"_id": {
"$oid": "628f739398580cae9c21b44f"
},
"place":"Amsterdam",
"events": [
{
"eventName": "Event one",
"eventText": "Event",
"eventDate": "010101"
"host":"Bob"
},
{
"eventName": "E2",
"eventText": "e2",
"eventDate": "020202"
"host":"John"
}
]
}
{
"_id": {
"$oid": "628f739398580cae9c21b44f"
},
"place":"London",
"events": [
{
"eventName": "e3",
"eventText": "e3",
"eventDate": "010101",
"host":"Bob"
}
]
}
And I want to get the array block of events being hosted by Bob, how would I do that? I have tried to use $elemSelector
like this:
const result = await mongoDatabase
.collection("temp")
.find({ events: { $elemMatch: { eventName: "E2" } } })
.toArray();
console.log(JSON.stringify({ result }));
But it just returns all events at the same place as the selected, Amsterdam in this case.
Wanted result:
{
"eventName": "Event one",
"eventText": "Event",
"eventDate": "010101"
"host":"Bob"
},
{
"eventName": "e3",
"eventText": "e3",
"eventDate": "010101",
"host":"Bob"
}
4
Answers
Try with this.
Check this out
And you can play around with more test data here: https://mongoplayground.net/p/A1UbZdZgZmr
You can achieve with simple pipeline stages
Playground
Following Structure can be achieved by using projection query in MongoDB one lucid solution for the above can be this