skip to Main Content

I’ve trying to create an endpoint in my API which return the youngest and oldest person from my database using mongodb e mongoose.

My database looks like that:

{
"message": "Employees list",
"result": [
    {
        "_id": "62562137bd9acaa47a13e2d2",
        "name": "Anakin Skywalker",
        "email": "[email protected]",
        "department": "Architecture",
        "salary": 4000,
        "birth_date": "1983-01-01T03:00:00.000Z",
        "__v": 0
    },
    {
        "_id": "625873509d27198519c460cb",
        "name": "pedro",
        "email": "[email protected]",
        "department": "Architecture",
        "salary": 700000,
        "birth_date": "1988-01-01T02:00:00.000Z",
        "__v": 0
    },
    {
        "_id": "6258b2bb6f4786b217624c2d",
        "name": "Henrique Skywalker",
        "email": "[email protected]",
        "department": "INfra",
        "salary": 9000,
        "birth_date": "1991-01-01T02:00:00.000Z",
        "__v": 0
    },
    {
        "_id": "6258b3066f4786b217624c31",
        "name": "perycles Skywalker",
        "email": "[email protected]",
        "department": "INfra",
        "salary": 9000000,
        "birth_date": "1990-01-01T02:00:00.000Z",
        "__v": 0
    },
    {
        "_id": "6258c38dca6a1013e80dbd2f",
        "name": "pdsdss Skywalker",
        "email": "[email protected]",
        "department": "INfra",
        "salary": 9000000,
        "birth_date": "1990-01-01T02:00:00.000Z",
        "__v": 0
    },
    {
        "_id": "625cbdae195853285e21fead",
        "name": "leia Skywalker",
        "email": "[email protected]",
        "department": "Data",
        "salary": 4500,
        "birth_date": "1978-01-01T03:00:00.000Z",
        "__v": 0
    }
]

And I need a query response like this one bellow:

{
  "younger": {
    "id": "1",
    "name": "Anakin Skywalker",
    "email": "[email protected]",
    "department": "Architecture",
    "salary": "4000.00",
    "birth_date": "01-01-1983"},
  "older": {
    "id": "2",
    "name": "Obi-Wan Kenobi",
    "email": "[email protected]",
    "department": "Back-End",
    "salary": "3000.00",
    "birth_date": "01-01-1977"},
  "average": "40.00"
}

My connection with mongoDb by mongoose was created like the example bellow:

const mongoose = require("mongoose");
require('dotenv').config();

const dataBase = () => mongoose.connect(
  process.env.URI,
  { useNewUrlParser: true, useUnifiedTopology: true },
  () => {
    console.log('Connected to MongoDB');
  }
);

module.exports = dataBase;

My mongoose schema looks like:

const mongoose = require("mongoose");
const User = new mongoose.Schema({
    name: {
      type: String,
      required: true,
    },
    email: {
      type: String,
      required: true,
    },
    password: {
      type: String,
      required: true,
    },
    department: {
      type: String,
      required: true,
    },
    salary: {
      type: Number,
      required: true,
    },
    birth_date: {
      type: Date,
      required: true,
    },
  });

module.exports = mongoose.model("User", User);

And my model layer is importing the connection file like that:

const model = require("../models/app.model");

Nonetheless I don’t be able to customize the data form and sort it as well. I appreciate any help in advantage

2

Answers


  1. db.getCollection('').find({}).sort({birth_date:-1})

    This will sort your collection in descending order by birth_date

    Login or Signup to reply.
  2. Find max or min then filter the array.

    db.collection.aggregate([
      {
        $match: { message: "Employees list" }
      },
      {
        $project: {
          younger: {
            $first: {
              $filter: {
                input: "$result",
                as: "r",
                cond: { $eq: [ "$$r.birth_date", { $max: "$result.birth_date" } ] }
              }
            }
          },
          older: {
            $first: {
              $filter: {
                input: "$result",
                as: "r",
                cond: { $eq: [ "$$r.birth_date", { $min: "$result.birth_date" } ] }
              }
            }
          },
          avg: {
            $subtract: [
              { $year: "$$NOW" },
              {
                $year: {
                  $toDate: {
                    $avg: {
                      $map: {
                        input: "$result",
                        as: "r",
                        in: { $toLong: { $toDate: "$$r.birth_date" } }
                      }
                    }
                  }
                }
              }
            ]
          }
        }
      }
    ])
    

    mongoplayground

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search