MongoDb: aggregation $lookup with filtering over the foreign documents

前端 未结 1 1487
一向
一向 2021-02-04 05:56

Given a couple of collecitons:

1.- USERS

{
  name: ...
  id: ...
  city: ...
  age: ...
  otherdata: ...
}

2.- PETS

{
          


        
相关标签:
1条回答
  • 2021-02-04 06:52

    You can use $filter array aggregation operator on pets array that is produced by your $lookup stage.

    To output pets older than 1 year use

    db.users.aggregate([ 
    { 
      $lookup: 
      { 
        from: "pets", 
        localField: "id", 
        foreignField: "owner", 
        as: "pets" 
      } 
    }, 
    {
      $project: 
      {
        name: 1,
        pets: 
        { 
          $filter: 
          { 
            input: "$pets", 
            as: "pet", 
            cond: { $gte: [ "$$pet.age", 1 ] } 
          } 
        } 
      } 
    } 
    ]);
    

    To output the oldest pets simply replace cond field of $filter operator in the previous aggregation pipeline with

    cond: { $eq: [ "$$pet.age", { $max: "$pets.age" } ] }
    
    0 讨论(0)
提交回复
热议问题