mehdi parastar
mehdi parastar

Reputation: 827

how to use $project with condition?

I have a collection as below:

[
  {
    "a": 1,
    "b": [
      {
        "a": 1,
        "bb": 10
      },
      {
        "a": 1,
        "bb": 11
      }
    ]
  },
  {
    "a": 2,
    "b": [
      {
        "a": 2,
        "bb": 20
      },
      {
        "a": 1,
        "bb": 21
      }
    ]
  },
]

in each row of the top collection I have two keys :

a and b

'b' key is an array of objects with [a, bb] keys.

now, I want to retrieve items of subarray(b) that the key exists in each row.

I want the result to be like this:

[
  {
    "a": 1,
    "bb": 10
  },
  {
    "a": 2,
    "bb": 20
  },
]

Do you have any idea to solve this?

MongoDB Playground

Upvotes: 0

Views: 413

Answers (1)

mohammad Naimi
mohammad Naimi

Reputation: 2359

use this aggregation in result you have a value and your result as gg if you need something else notify me

db.collection.aggregate([
{
    '$project': {
      'a': 1, 
      'gg': {
        '$filter': {
          'input': '$b', 
          'as': 'z', 
          'cond': {
            '$eq': [
              '$$z.a', '$a'
            ]
          }
        }
      }
    }
  }
])

Upvotes: 1

Related Questions