草庐IT

Mongodb 聚合框架和嵌套 $lookup

coder 2023-10-31 原文

我正在尝试使用 mongodb 的聚合框架来进行嵌套填充,但我遇到了一些麻烦。

这是我拥有的初始数据:

[
  {
    _id: ObjectId('123'),
    profileId: ObjectId('456')
  },
  // ...other documents
]

我将此聚合管道应用于它,以便我可以使用 profileId 字段填充 profile 字段:

MyModel.aggregate([
  {
    $lookup: {
      from: 'profiles',
      localField: 'profileId',
      foreignField: '_id',
      as: 'profile'
    }
  },
  {
    $project: {
      profile: {
        $arrayElemAt: [ '$profile', 0 ]
      },
      profileId: 1,
    }
  },
]

这是结果:

[
  {
    _id: ObjectId('123'),
    profileId: ObjectId('456'),
    profile: {
      grades: [
        ObjectId('...'),
        ObjectId('...')
      ]
      // ... other props
    }
  }
  // ...other documents
]

现在我通过添加 $lookup 来扩展管道,以填充每个 profile 文档中的成绩:

MyModel.aggregate([
  {
    $lookup: {
      from: 'profiles',
      localField: 'profileId',
      foreignField: '_id',
      as: 'profile'
    }
  },
  {
    $project: {
      profile: {
        $arrayElemAt: [ '$profile', 0 ]
      },
      profileId: 1,
    }
  },
  {
    $lookup: {
      from: 'profile-grades',
      localField: 'profile._id',
      foreignField: 'profile',
      as: 'profile.grades'
    }
  }
]

这是目前的结果:

[
  {
    _id: ObjectId('123'),
    profileId: ObjectId('456'),
    profile: {
      grades: [
        {
          studyLocationId: ObjectId('789'),
          // ... other props
        },
        // ... other grades
      ]
    }
  }
  // ...other documents
]

我无法实现的最后一步是 grades 数组中每个 studyLocation 的人口。

想要的结果:

[
  {
    _id: ObjectId('123'),
    profileId: ObjectId('456'),
    profile: {
      grades: [
        {
          studyLocationId: ObjectId('789'),
          studyLocation: {
            _id: ObjectId('...'),
            // other props
          },
        },
        // ... other grades
      ]
    }
  }
  // ...
]

我尝试添加另一个 $lookup 阶段,但没有成功:

  {
    $lookup: {
      from: 'study-locations',
      localField: 'profile.grades.studyLocationId',
      foreignField: '_id',
      as: 'profile.grades.studyLocation'
    }
  }

这只是返回:

grades: {
   studyLocation: []
}

我应该怎么做?这可能吗? 谢谢!

最佳答案

如果您使用的是 mongodb3.4,这将有效,对于以前的版本,您需要在等级上展开运算符。

关于Mongodb 聚合框架和嵌套 $lookup,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45879677/

有关Mongodb 聚合框架和嵌套 $lookup的更多相关文章

  1. ruby-on-rails - Rails 编辑表单不显示嵌套项 - 2

    我得到了一个包含嵌套链接的表单。编辑时链接字段为空的问题。这是我的表格:Editingkategori{:action=>'update',:id=>@konkurrancer.id})do|f|%>'Trackingurl',:style=>'width:500;'%>'Editkonkurrence'%>|我的konkurrencer模型:has_one:link我的链接模型:classLink我的konkurrancer编辑操作:defedit@konkurrancer=Konkurrancer.find(params[:id])@konkurrancer.link_attrib

  2. ruby - 将散列转换为嵌套散列 - 2

    这道题是thisquestion的逆题.给定一个散列,每个键都有一个数组,例如{[:a,:b,:c]=>1,[:a,:b,:d]=>2,[:a,:e]=>3,[:f]=>4,}将其转换为嵌套哈希的最佳方法是什么{:a=>{:b=>{:c=>1,:d=>2},:e=>3,},:f=>4,} 最佳答案 这是一个迭代的解决方案,递归的解决方案留给读者作为练习:defconvert(h={})ret={}h.eachdo|k,v|node=retk[0..-2].each{|x|node[x]||={};node=node[x]}node[

  3. Ruby——嵌套类和子类是一回事吗? - 2

    下面例子中的Nested和Child有什么区别?是否只是同一事物的不同语法?classParentclassNested...endendclassChild 最佳答案 不,它们是不同的。嵌套:Computer之外的“Processor”类只能作为Computer::Processor访问。嵌套为内部类(namespace)提供上下文。对于ruby​​解释器Computer和Computer::Processor只是两个独立的类。classComputerclassProcessor#Tocreateanobjectforthisc

  4. ruby - 模块嵌套代码风格偏好 - 2

    我的假设是moduleAmoduleBendend和moduleA::Bend是一样的。我能够从thisblog找到解决方案,thisSOthread和andthisSOthread.为什么以及什么时候应该更喜欢紧凑语法A::B而不是另一个,因为它显然有一个缺点?我有一种直觉,它可能与性能有关,因为在更多命名空间中查找常量需要更多计算。但是我无法通过对普通类进行基准测试来验证这一点。 最佳答案 这两种写作方法经常被混淆。首先要说的是,据我所知,没有可衡量的性能差异。(在下面的书面示例中不断查找)最明显的区别,可能也是最著名的,是你的

  5. ruby-on-rails - 使用回形针的嵌套形式 - 2

    我有一个名为posts的模型,它有很多附件。附件模型使用回形针。我制作了一个用于创建附件的独立模型,效果很好,这是此处说明的View(https://github.com/thoughtbot/paperclip):@attachment,:html=>{:multipart=>true}do|form|%>posts中的嵌套表单如下所示:prohibitedthispostfrombeingsaved:@attachment,:html=>{:multipart=>true}do|at_form|%>附件记录已创建,但它是空的。文件未上传。同时,帖子已成功创建...有什么想法吗?

  6. ruby-on-rails - Rails 3,嵌套资源,没有路由匹配 [PUT] - 2

    我真的为这个而疯狂。我一直在搜索答案并尝试我找到的所有内容,包括相关问题和stackoverflow上的答案,但仍然无法正常工作。我正在使用嵌套资源,但无法使表单正常工作。我总是遇到错误,例如没有路线匹配[PUT]"/galleries/1/photos"表格在这里:/galleries/1/photos/1/edit路线.rbresources:galleriesdoresources:photosendresources:galleriesresources:photos照片Controller.rbdefnew@gallery=Gallery.find(params[:galle

  7. TimeSformer:抛弃CNN的Transformer视频理解框架 - 2

    Transformers开始在视频识别领域的“猪突猛进”,各种改进和魔改层出不穷。由此作者将开启VideoTransformer系列的讲解,本篇主要介绍了FBAI团队的TimeSformer,这也是第一篇使用纯Transformer结构在视频识别上的文章。如果觉得有用,就请点赞、收藏、关注!paper:https://arxiv.org/abs/2102.05095code(offical):https://github.com/facebookresearch/TimeSformeraccept:ICML2021author:FacebookAI一、前言Transformers(VIT)在图

  8. ruby - 如何根据长度将路径数组转换为嵌套数组或散列 - 2

    我需要根据字符串路径的长度将字符串路径数组转换为符号、哈希和数组的数组给定以下数组:array=["info","services","about/company","about/history/part1","about/history/part2"]我想生成以下输出,对不同级别进行分组,根据级别的结构混合使用符号和对象。产生以下输出:[:info,:services,about:[:company,history:[:part1,:part2]]]#altsyntax[:info,:services,{:about=>[:company,{:history=>[:part1,:pa

  9. ruby-on-rails - 使用 rspec 和 rails 测试嵌套模块 - 2

    这个问题在这里已经有了答案:关闭10年前。PossibleDuplicate:Testingmodulesinrspec目前我正在使用rspec成功测试我的模块,如下所示:require'spec_helper'moduleServicesmoduleAppServicedescribeAppServicedodescribe"authenticate"doit"shouldauthenticatetheuser"dopending"authenticatetheuser"endendendendend我的模块位于应用程序/服务/services.rb应用程序/服务/app_servi

  10. ruby-on-rails - 嵌套模型验证 - 错误不显示 - 2

    关于这个有很多问题,但似乎都没有帮助。是的,我看过thisrailscast.我有一个作者,他有很多书,像这样:作者:classAuthor书:classBook我创建了以下表单以在authors#show中向作者添加一本书:#labelsandbuttons......使用以下authors_controller方法:defshow@author=Author.find(params[:id])@book=@author.books.buildend...以及以下books_controller方法:defcreate@author=Author.find(params[:autho

随机推荐