Harry Edward
Harry Edward

Reputation: 151

How to use aggregate map and filter for multiple arrays in Mongodb

Here i have Two arrays,

 Usercar = [{
            parentId :001
            cars:[
                   {_id: 1, name: bmw, color: red},
                   {_id: 2, name: Ford, color: black},
                   {_id: 3, name: Volkswagen, color: black},
                 ]
              }]


 Userfavorite = 
               [{
                  parentId :001,
                  favoriteCars:[1,3] //mongoose.Types.ObjectId
               }]

I want o show user favorite cars using mongodb aggregate, here is my code

let carsId= [1,3];


    {$match: {
        parentId :001
    }},
    {
        $project:{
            cars:{
                $filter:{

                        input:"$cars",
                        as :'cars',
                        cond:{ $eq :["$$cars._id", mongoose.Types.ObjectId('1')]}
                      //cond:{ $eq :["$$cars._id", carsId]}
                }
            }
        }
    }

the above code only work, when pass single carsId, I want user favorite Cars details from Usercar's collection, how to do that in mongodb aggregate ?

Upvotes: 0

Views: 1071

Answers (1)

Joe
Joe

Reputation: 28326

One possible aggregate that could do this is:

  • aggregate on the Usercar collection
  • lookup the matching document from the Userfavorite collection
  • in case there are multiple favorite documents, combine them into a single favorite array
  • reduce the cars collection to find those matching the favorites, and add to an array
db.Usercar.aggregate([
  {$lookup: {
      from: "Userfavorite",
      localField: "parentId",
      foreignField: "parentId",
      as: "favorite"
  }},
  {$set: {
      favorite: {
        $arrayElemAt: [
          {$concatArrays: "$favorite.favoriteCars"},
          0
        ]
      }
  }},
  {$addFields: {
      favoriteCarDetails: {
        $filter: {
          input: "$cars",
          cond: {
            $in: [
              "$$this._id",
              "$favorite"
            ]
          }
        }
      }
  }}
])

Playground

Upvotes: 1

Related Questions