1

I have the following issue when I try to match elements in an array based on the value in one of the array subfields.

Example document structure:

{
    "A" : {
        "C" : "abc"
    },
    "B" : [ 
        {
            "C" : "def"
        }, 
        {
            "C" : "ghi"
        }, 
        {
            "C" : "jkl"
        }, 
        {
            "C" : "abc"
        }
    ]
}

Example result document:

{
    "A" : {
        "C" : "abc"
    },
    "B" : [ 
        {
            "C" : "abc"
        }
    ]
}

My attempt:

db.collection.aggregate([
    {'$match': {
        'B.C': 'A.C'
        }},
    {'$project': {
        'A.C': 1,
        'B.C': 1
        }}
])

Where am I making an error?

Thanks!

Ashh
  • 44,693
  • 14
  • 105
  • 132
CHRD
  • 1,917
  • 1
  • 15
  • 38

2 Answers2

1

You can use $filter aggregation here

db.collection.aggregate([
  { "$addFields": {
    "B": {
      "$filter": {
        "input": "$B",
        "cond": { "$eq": ["$$this.C", "$A.C"] }
      }
    }
  }}
])
Ashh
  • 44,693
  • 14
  • 105
  • 132
  • Thanks, that works! Would you mind explaining the issue with the way I attempted to do it? That is, using `$match`. – CHRD Jan 27 '20 at 11:29
  • You have completely misunderstood the aggregation here. `$match` `'B.C': 'A.C'` doesn't make any sense. Even if you want to [match the two fields from the document you have to use `$expr`](https://stackoverflow.com/questions/4442453/mongodb-query-condition-on-comparing-2-fields). And if you want to get an updated array so basically you need some array operator(as `$filter` here) to do so. – Ashh Jan 27 '20 at 11:32
0

You can simply loop into a sub array by using the qry part

mainarray.subarray name

eg : B.C
Ananthu M
  • 77
  • 5