Can we find documents with filtering Array Field Using find()?

I’ve some data in following format

[
	{
		_id: 1,
		city: 'ABC',
		values: [
			{ query: 'aa', isResolve: true },
			{ query: 'ba', isResolve: false },
			{ query: 'ca', isResolve: false },
		]
	}, 
	{
		_id: 2,
		city: 'ABC'
		values: [
			{ query: 'ab', isResolve: true },
			{ query: 'bb', isResolve: true },
			{ query: 'cb', isResolve: false },
		]
	}, 
	{
		_id: 3,
		city: 'XYZ'
		values: [
			{ query: 'aba', isResolve: false },
			{ query: 'bba', isResolve: false },
			{ query: 'cba', isResolve: false },
		]
	}
]

now i want to find documents along with filtering the arrays - values.

some thing like, match {city: ‘ABC’} and filters values array based on { isResolved: false }.

so my output should be

[
	{
		_id: 1,
		city: 'ABC',
		values: [
			{ query: 'ba', isResolve: false },
			{ query: 'ca', isResolve: false },
		]
	}, 
	{
		_id: 2,
		city: 'ABC'
		values: [
			{ query: 'cb', isResolve: false },
		]
	},
]

can we even do this in a single model.find() ?

Hello @Raziq_Ali, Welcome,

Of course we can, simply using $filter operator,

model.find(
  { city: "ABC" },
  {
    city: 1,
    values: {
      $filter: {
        input: "$values",
        cond: {
          $eq: ["$$this.isResolve", false]
        }
      }
    }
  }
)
2 Likes

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