首页 > 解决方案 > 如何聚合嵌套属性中的查找?

问题描述

我有一个连接到 mongo db 的 Java Spring 应用程序。

在那个数据库中,我有两个集合:

atas 包含具有以下架构的文档:

{
  ata: string,
  description: string
}

包含具有以下架构的文档的更正:

{
   //some properties
   predictions: [
       {ata: string, accuracy: float}
   ],
   //other properties
}

我想在 atas 集合的 ata 属性和更正属性的 predictions 属性的 ata 属性上“加入”这两个集合,以便我最终得到一个文档

{
    //some properties
    predictions: [
      {ata: string, description: string, accuracy: float}
    ]
}

或者

{

   //some properties
   predictions: [
      {ata: {ata: string, description}, accuracy: float}
   ]

}

如何在 mongo 中做到这一点?

我使用以下代码来查看是否至少可以为每个预测获得正确的 ata 文档。

db.getCollection('corrections').aggregate([
{
    $lookup: 
    {
        from: "atas",
        localField: "predictions.ata",
        foreignField: "ata",
        as: "atas"
    }
}])

它在结果文档中为我提供了正确的 ata(如果它存在于 atas 集合中)。

现在我希望能够在每个文档的预测属性中的对象的 ata 属性中包含这些 atas,如上所述。

如果我的要求不明确,请不要犹豫,不要问我问题。

提前感谢您给我的任何帮助或时间。

PS:我用 java 和 spring 标记是因为我想在 Spring 中实现它,但首先我想看看如何在纯 mongo 中实现它。

标签: javaspringmongodblookupaggregation

解决方案


推荐阅读