implementing flatten logic in mongo