MongoDB汇总,返回所有文档,其中$查找的外国文档不存在

发布于 2025-01-30 15:33:33 字数 518 浏览 5 评论 0原文

我现在正在使用CMS系统,如果删除页面,则没有关联的内容。就我的一位客户而言,这已经变得繁重了,因为我们现在随着时间的推移积累了数百万个内容文档,并且使每日功能执行DBS,备份DBS,备份DBS等都使其令人难以置信。

请考虑此结构:

页面:页面:页面:页面:页面文档:

{
  _id: pageId,
  contentDocumentId: someContentDocId
}

内容文档:

{
  _id: someContentDocId,
  page_id: pageId,
  content: [someContent, ...etc]
}

有没有一种方法来制作mongoDB聚合,我们基于检查page_id汇总内容文档,如果我们检查了page> page_id返回null,则我们汇总那个文档?这不像外国菲尔德(Exourthfield)那样简单,在设置为null的$查找中,是吗?

I'm working with a CMS system right now where if pages are deleted the associated content isn't. In the case of one of my clients this has become burdensome, as we now have millions of content docs accumulated over time, and it's making it prohibitive to do daily functions, like restoring dbs, backing up dbs, etc.

Consider this structure:

Page document:

{
  _id: pageId,
  contentDocumentId: someContentDocId
}

Content document:

{
  _id: someContentDocId,
  page_id: pageId,
  content: [someContent, ...etc]
}

Is there a way to craft a MongoDB aggregation where we aggregate Content docs based on checking page_id, and if our check for page_id returns null, then we aggregate that doc? It's not something as simple as foreignField in a $lookup being set to null, is it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

节枝 2025-02-06 15:33:33

这应该解决问题:

db.content.aggregate([
  {
    "$lookup": {
      "from": "pages",
      "localField": "page_id",
      "foreignField": "_id",
      "as": "pages"
    }
  },
  {
    "$addFields": {
      "pages_length": {
        "$size": "$pages"
      }
    }
  },
  {
    "$match": {
      "pages_length": 0
    }
  },
  {
    "$unset": [
      "pages",
      "pages_length"
    ]
  }
])

我们从content集合中创建一个聚合,并使用pages Collection进行正常$ loopup。当找不到匹配页面时,数组页面将为[],因此我们只需过滤数组为空的每个文档即可。

您不能使用$ size内部$ match来过滤数组长度,因此我们需要创建一个临时字段pages_length存储数组。

最后,我们使用$ unset删除临时字段。

Playground

This should do the trick:

db.content.aggregate([
  {
    "$lookup": {
      "from": "pages",
      "localField": "page_id",
      "foreignField": "_id",
      "as": "pages"
    }
  },
  {
    "$addFields": {
      "pages_length": {
        "$size": "$pages"
      }
    }
  },
  {
    "$match": {
      "pages_length": 0
    }
  },
  {
    "$unset": [
      "pages",
      "pages_length"
    ]
  }
])

We create an aggregation from the content collection and do a normal $loopup with the pages collection. When no matching page is found, the array pages will be [] so we just filter every document where the array is empty.

You can't use $size inside $match to filter array lengths, so we need to create a temporary field pages_length to store the length of the array.

In the end we remove the temporary fields with $unset.

Playground

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文