Home > Back-end >  Get aggregate with lookup in single Object
Get aggregate with lookup in single Object

Time:11-28

my problem is how I get a simple object of ownerDetails, correct me if my code is wrong

data I got, from my code


    {
    "status": true,
    "data": [
        {
            "_id": "61a2a9680b122bc154cbd6af",
            "ownerName": "Ajay",
            "mobile": 878787878,
            "designation": "IT",
            "gender": "Male",
            "age": 26,
            "carDetails": [
                {
                    "carName": "BUY",
                    "color": "blue",
                    "sheets": 8,
                    "avgSpeed": 105,
                    "price": 850000,
                    "model": "C110"
                },
                {
                    "carName": "GTR",
                    "color": "blue",
                    "sheets": 4,
                    "avgSpeed": 105,
                    "price": 98000,
                    "model": "G120"
                }
            ]
        }
    ]
}

i want data like this,


    {
    "status": true,
    "ownerDetails":  {
            "_id": "61a2a9680b122bc154cbd6af",
            "ownerName": "Ajay",
            "mobile": 878787878,
            "designation": "IT",
            "gender": "Male",
            "age": 26,
            "total_car": 2,
        }
}

code for getting data from collections


    exports.getOwnerDetails = async (req, res, next) => {

  try {
    Owner.aggregate([
      {
        $match: { ownerName: req.body.ownerName }
      },

      {
        $lookup: {
          from: "cars",
          localField: "ownerName",
          foreignField: "ownerName",
          as: "carDetails",
        },
      },
      {
        $project: {
          "carDetails._id": 0,
          "carDetails.ownerName": 0,
        },
      },
    ]).then((data) => {
      res.json({
        status: true,
        data: data,
      });
    });
  } catch (error) {
    res.status(500).json({
      status: false,
      msg: "Error : "   error,
    });
  }
};


in may returning data, I got an array of carDetails, but I only need that how many are owned by an Owner, and return a simple object of ownerDetails

CodePudding user response:

$lookup return an array because more than one values can match the join. If you want to get only one value you can get the first element from the array. Then you can add these aggregation stages:

  • First $addFields to get the first element from the array (index 0).
  • Then use $project to get the desired output.
{
  "$addFields": {
    "data": {
      "$arrayElemAt": ["$data",0]
    }
  }
},
{
  "$project": {
    "status": 1,
    "ownerDetails": {
      "_id": "$data._id",
      "ownerName": "$data.ownerName",
      "mobile": "$data.mobile",
      "designation": "$data.designation",
      "gender": "$data.gender",
      "age": "$data.age",
      "total_car": {
        "$size": "$data.carDetails"
      }
    }
  }
}

Example here

CodePudding user response:

Query

  • i am not sure if this is what you want
  • unwind all owners from data
  • and from each owner, count its cars number

Test code here

aggregate(
[{"$unwind": {"path": "$data"}},
 {"$set": 
   {"data.total_car": {"$size": "$data.carDetails"},
    "data.carDetails": "$$REMOVE",
    "_id": "$$REMOVE"}},
 {"$set": {"ownerDetails": "$data", "data": "$$REMOVE"}}])
  • Related