Aggregate : Filter Data And Only Return Matched Criteria

This could be a simple question but I am not sure how to proceed.

The below is a customer address collection I have :

    [
      {
        _id: ObjectId("61303d11c9ed16df15b18cdf"),
        CustomerID: 1234533,
        address: [
          {
            addresstype: 'Primary',
            address1: '33rd Street',
            city: 'New York',
            state: 'NY',
            zipcode: '45875'
          },
          {
            addresstype: 'Secondary',
            address1: '44th Street',
            city: 'New York',
            state: 'NY',
            zipcode: '45880'
          }
        ]
      },
      {
        _id: ObjectId("61303d17c9ed16df15b18ce0"),
        CustomerID: 1234534,
        address: [
          {
            addresstype: 'Primary',
            address1: 'Dovion Street',
            city: 'Chicago',
            state: 'OH',
            zipcode: '54212'
          },
          {
            addresstype: 'Secondary',
            address1: 'Maple Street',
            city: 'Chicago',
            state: 'OH',
            zipcode: '54505'
          }
        ]
      }
    ]

From this collection, I would like to return Only the Primary address of the customer.

But, when I run the below aggregate command with filter on address type, it returns me both Primary and Secondary address:

    db.CustomerAddress.aggregate([
    		{
    			$match : {
    				"address.addresstype" : {$eq : 'Primary'}
    			}
    		},
    		{
    			$project : {CustomerID:1,"address.addresstype" : 1, _id : 0,"address.address1" : 1}
    		}
    	])

Output:

     [
      {
        CustomerID: 1234533,
        address: [
          { addresstype: 'Primary', address1: '33rd Street' },
          { addresstype: 'Secondary', address1: '44th Street' }
        ]
      },
      {
        CustomerID: 1234534,
        address: [
          { addresstype: 'Primary', address1: 'Dovion Street' },
          { addresstype: 'Secondary', address1: 'Maple Street' }
        ]
      }
    ]

What am I missing here?

Hi @Vikram_Bade ,

In the project stage you have to use $filter operator and input address array while filtered condition should only pick Primary address.

Thanks
Pavel

Thank You Pavel. That worked:

db.CustomerAddress.aggregate([
	{
		$project : 
			{
				address: {
					$filter: {
					   input: "$address",
					   as: "filteredaddress",
					   cond: { $eq: [ "$$filteredaddress.addresstype", 'Primary' ] }
					}
				},
				CustomerID:1
				, _id : 0
			}
	}
])
1 Like

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