How to query an object array and return only objects that match mongo/mongoose

I have the collection below and would like to return all matches where firstParticipant.address or secondParticipant.address = 789 how to make this query with the mongoose and return only the objects that match the filter?

My document:

     {
        	"_id": "25113",
        	"title": "Jogo de futebol",
        	"rounds": {
        		"matches": [{
        				"firstParticipant": {
        					"address": "789",
        					"battlesWon": 0
        				},
        				"secondParticipant": {
        					"address": "748569874",
        					"battlesWon": 0
        				}
        			},
        			{
        				"firstParticipant": {
        					"address": "963",
        					"battlesWon": 0
        				},
        				"secondParticipant": {
        					"address": "741",
        					"battlesWon": 0
        				}
        			},
        			{
        				"firstParticipant": {
        					"address": "258",
        					"battlesWon": 0
        				},
        				"secondParticipant": {
        					"address": "789",
        					"battlesWon": 0
        				}
        			}
        		]
        	}
        }

Expected result:

expected result:

     [{
    		"firstParticipant": {
    			"address": "789",
    			"battlesWon": 0
    		},
    		"secondParticipant": {
    			"address": "748569874",
    			"battlesWon": 0
    		}
    	},
    	{
    		"firstParticipant": {
    			"address": "258",
    			"battlesWon": 0
    		},
    		"secondParticipant": {
    			"address": "789",
    			"battlesWon": 0
    		}
    	}
    ]

Hi @Daywison_Ferreira_Leal, welcome to the community.
The $elemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria.

{ <field>: { $elemMatch: { <query1>, <query2>, ... } } }

Hopefully, it will help you in achieving the expected behavior.

In case you have any doubts, please feel free to reach out to us.

Thanks and Regards.
Sourabh Bagrecha

3 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.