Reputation: 850
I have a data structure in mongoDB looking this way
{_id:ObjectId(''),
"awards" : [
{
"award" : "Ballon d'Or",
"numberOfTimes" : 6
},
{
"award" : "Golden Boot",
"numberOfTimes" : 6
},
{
"award" : "FIFA World Player of the Year",
"numberOfTimes" : 1
}
],
push:true
}
I am currently using this moongose filter {'awards.award':"Ballon d'Or"}
I would like to only return the object that matches Ballon d'Or only in the awards array
so the output will looke like this
{_id:ObjectId(''),
"awards" : [
{
"award" : "Ballon d'Or",
"numberOfTimes" : 6
}
],
push:true
}
THANKS
Upvotes: 0
Views: 2204
Reputation: 386
you can simply use a the positionnal operator $ to achieve this :
const = await YourModel.find({'awards.award':"Ballon d'Or"}, "awards.$");
The problem here would be if you have many footballers having this medal. You should add their name in the query. Also only the first award that match the query will be returned
Another approach would consist in creating another model and use foreign keys inspired by relationnal DB
Upvotes: 1
Reputation: 9268
You can use projection operator '$'
for this:
You can try:
db.collection.find({'awards.award':"Ballon d'Or"}, {'awards.$' : 1})
awards.$:1
will only return the matching object from the awards array.
Note: $(projection)
operator returns only first matched element of array
Alternate:
If you want all the matched elements, you can use aggregation pipeline. You will need to first unwind awards array, apply the filter to get the desired results only, and group them back again to get the array back.
Try this for aggregation pipeline:
db.collection.aggregate([
{
"$unwind": "$awards"
},
{
$match: {
"awards.award": "Ballon d'Or"
}
},
{
$group: {
_id: "$_id",
push: {
$first: "$push"
},
awards: {
$push: "$awards"
}
}
}
])
Have a look at this MongoDB playground to play with aggregation pipeline.
Upvotes: 2
Reputation: 341
You can use Aggregate unwind pipeline.
First, you can unwind the array elements. Unwind breaks array elements into documents(or objects). Then Search for your required docs.
Model.aggregate([
$unwind: '$awards',
$match : {'$award':"Ballon d'Or"}
])
Upvotes: 1