MongoDb:聚合$ lookup并过滤外部文档 [英] MongoDb: aggregation $lookup with filtering over the foreign documents

查看:431
本文介绍了MongoDb:聚合$ lookup并过滤外部文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出几个大学跳棋:

1.-用户

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

2.- PETS

{
  name: ...
  owner: ...
  type: ...
  age: ...
}

我正在尝试将聚合与$ lookup结合使用来构建一组对象,这些对象代表宠物的用户:

I'm trying to use aggregation with $lookup to build a set of objects that represent users with their pets:

collectionusers.aggregate([
   {
     $lookup: {
       from: "pets",
       localField: "id",
       foreignField: "owner",
       as: "pets"
     }
   }
]);

但是我想添加一个过滤器,以便仅将超过1年的宠物添加到每个用户中(使用宠物对象内的字段年龄).

But I'd like to add a filter so that only pets older than 1 year are added to each user (using field age inside the pet objects).

问题是,在聚合中添加$ match不起作用,因为它会筛选出没有旧宠物的用户,我希望用户即使没有宠物也要在那里.

The problem is, adding $match in the aggregation does not work because it filters out users without old pets, and I want the users to be there even if they don't have pets.

实际上,我也试图以相同的方式获取每个用户中最老的宠物,但我也没有找到公式.

Actually I'm also trying to get only the oldest of the pets of each user in the same way and I also didn't find the formula.

在聚合中执行此操作的任何方法吗?

Any way to perform this action within the aggregation?

当然,目前我正在对返回的对象执行此操作.

Of course, currently I'm doing it afterwards, on the returned objects.

谢谢.

推荐答案

您可以使用

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

要输出使用1年以上的宠物

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 ] } 
      } 
    } 
  } 
} 
]);

要输出最老的宠物,只需将先前聚合管道中$filter运算符的cond字段替换为

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" } ] }

这篇关于MongoDb:聚合$ lookup并过滤外部文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆