CHRD
CHRD

Reputation: 1957

MongoDB match subfield in array

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!

Upvotes: 1

Views: 1211

Answers (2)

Ananthu M
Ananthu M

Reputation: 107

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

mainarray.subarray name

eg : B.C

Upvotes: 0

Ashh
Ashh

Reputation: 46481

You can use $filter aggregation here

db.collection.aggregate([
  { "$addFields": {
    "B": {
      "$filter": {
        "input": "$B",
        "cond": { "$eq": ["$$this.C", "$A.C"] }
      }
    }
  }}
])

Upvotes: 1

Related Questions