function scopePaths(array, fields, init) {
  if (!(init && fields)) {
    return undefined;
  }

  const path = array.path + '.';
  const keys = Object.keys(fields);
  let i = keys.length;
  const selected = {};
  let hasKeys;
  let key;
  let sub;

  while (i--) {
    key = keys[i];
    if (key.startsWith(path)) {
      sub = key.substring(path.length);
      if (sub === '$') {
        continue;
      }
      if (sub.startsWith('$.')) {
        sub = sub.substring(2);
      }
      hasKeys || (hasKeys = true);
      selected[sub] = fields[key];
    }
  }

  return hasKeys && selected || undefined;
}
Scopes paths selected in a query to this array.
Necessary for proper default application of subdocument values.

@param {DocumentArrayPath} array the array to scope `fields` paths
@param {Object|undefined} fields the root fields selected in the query
@param {Boolean|undefined} init if we are being created part of a query result
@api private