微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 Mongo 聚合管道从外部集合中的一组 ID 填充响应

如何解决使用 Mongo 聚合管道从外部集合中的一组 ID 填充响应

我目前正在使用 MERN 堆栈开发应用。

我有一个 User 模型,其中文档看起来如下

{
  username: 'Testuser',events: {
    favorited: [ObjectId("abcdefg12345678"),ObjectId("hijklmno12345678")]
  } 
}

然后我有一个 Event 模型,其中文档看起来如下

[
  {
    _id: ObjectId("abcdefg12345678"),name: 'Party One',address: 'Party St'
  },{
    _id: ObjectId("hijklmno12345678"),name: 'Party Two',address: 'Party Lane'
  },{
    _id: ObjectId("pqrstuvw12345678"),name: 'Party Three'
    address: 'Party Town'
  }
]

我只想返回与 User 文档中的 favorited 数组对应的 Event 文档的数组,并且我只想返回 Event name,而不是 address .

我认为我需要使用 $lookup$project,但到目前为止我的尝试都没有成功。

我最近的尝试看起来像这样。

User.aggregate([
  {
    $lookup: {
      from: "Event",localField: "events.favorited",foreignField: "name",as: "favorite_events"
    }
  },{
    $project: {
      id: 1,name: 1,}
  }
])
  • 更新以将 favorited 数组从 strings 更改为 ObjectIds

解决方法

修正:

  • from 写下您在数据库中的实际集合名称
  • foreignField 传递 _id 以将此字段与 events.favorited 匹配
  • as 返回 events.favorited 字段中的事件
  • $project 从事件 address
  • 中排除 events.favorited.address 字段
User.aggregate([
  {
    $lookup: {
      from: "events",// correct with yours collection name
      localField: "events.favorited",foreignField: "_id",as: "events.favorited"
    }
  },{ $project: { "events.favorited.address": 0 } }
])

Playground

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。