How to fetch only specified array element from nested array present in document

Hello, @Erica_01! Welcome to the community!

Ok, so you need to query the document and modify the output.
To achieve that you need to use and aggregation.

Example:

db.test1.aggregate([
  {
    // first, filter the documents, that contain
    // fields with necessary values
    $match: {
      'channel.name': 'switch',
      'channel.formats.formatName': 'ISO8583-93',
      'channel.formats.messages.name': 'balanceEnquiry',
    },
  },
  // the following $unwind stages will convert your arrays
  // to objects, so it would be easier to filter the messages
  {
    $unwind: '$channel.formats',
  },
  {
    $unwind: '$channel.formats.messages',
  },
  {
    // filter messages here
    $match: {
      'channel.formats.messages.name': 'balanceEnquiry',
    },
  },
  {
    // returns only message(s)
    $replaceWith: '$channel.formats.messages',
  },
]).pretty();
4 Likes