How can I filter entries based on the FieldValue.Alias and FieldValue.Value?

Hey @James_Kovacs,

I have a similar case to C# MongoDB filter a value from the following structure.

I have this structure:
image

How can I filter entries based on the FieldValue.Alias and FieldValue.Value?

So, the idea is to return all the entries that have “age” = 32.

I tried this: “{ $and: [{ “FieldValues.Alias”: “age”, “FieldValues.Value”: 32}]}” but it returns also the entries that have “age” = whatever, and another field (for example “no”) = 32.

Hi @Arbnor_Zeqiri - Welcome to the community :wave:

In future, I would recommend pasting sample documents as text rather than images as it makes reproducing, testing or troubleshooting for other community users easier :slight_smile: Check out Formatting code and log snippets in posts for more details on this.

I’m not sure what you’re expecting as the output, but I’ve created a example aggregation pipeline which may help you identify elements as you have specified. Please see the example aggregation operation and output below:

DB> db.data.find()
[
  {
    _id: ObjectId("62e20e051bb9515b8fbd4fed"),
    arrayField: [
      { value: 32, alias: 'age', type: 7 },
      { value: 2, alias: 'length', type: 8 }
    ]
  }
]
DB> y
{
  '$addFields': {
    filteredEntries: {
      '$filter': {
        input: '$arrayField',
        as: 'element',
        cond: {
          '$and': [
            { '$eq': [ '$$element.value', 32 ] },
            { '$eq': [ '$$element.alias', 'age' ] }
          ]
        }
      }
    }
  }
}


DB> db.data.aggregate(y)
/// Output:
[
  {
    _id: ObjectId("62e20e051bb9515b8fbd4fed"),
    arrayField: [
      { value: 32, alias: 'age', type: 7 },
      { value: 2, alias: 'length', type: 8 }
    ],
    filteredEntries: [ { value: 32, alias: 'age', type: 7 } ] /// <--- additional filtered array field
  }
]

For your reference, i’ve used the following aggregation stages / operators:

Additionally, you can perhaps play around with MongoDB Compass and check out the export aggregation pipeline to language feature which may help with regards to the C# mentioned in your post link.

Please test this thoroughly if you believe it may help and ensure it works for all your use case(s) and meets all your requirements.

If you require further assistance, please advise the following information:

  1. Sample documents
  2. Expected output
  3. MongoDB version

Regards,
Jason

1 Like