0

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 ?

3
  • @neil-lunn please take a look Commented Apr 22, 2020 at 3:37
  • 1
    Are Usercar and Userfavorite in the same document, or separate collections? Commented Apr 22, 2020 at 5:24
  • Its separate collections Commented Apr 22, 2020 at 5:26

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

favoriteCarDetails is empty :(
why we need concatArrays in the case ?
You don't necessarily, that just deals with the possibility that there are 2 matching documents in the other collection. If there will only ever be one, you can just project it or unwind it to pull it out of the looked up array

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.