【问题标题】:Query deep level nested documents with top level document id使用顶级文档 id 查询深层嵌套文档
【发布时间】:2021-04-09 14:05:05
【问题描述】:

我有三个级别的集合,即用户、部门和项目。这是它的结构,每个用户将拥有多个部门,每个部门将拥有多个项目。

user -> departments -> projects

我已经完成了其他类似的 mongodb 查询,但它们都没有解决我的具体问题。

这是我的整个数据结构的样子

{
"_id": "5a2ca2227c42ad67682731d4", // this is user id
"name": "XYZ Bank",
createdAt: "2021-04-08T04:05:30.340Z",
updatedAt: "2021-04-08T04:05:30.340Z",
"departments": [
    {
        "_id": "5a2ca2227c42ad6768271232",
        "name": "Digital",
        "userId": "5a2ca2227c42ad67682731d4",
        createdAt: "2021-04-08T04:05:30.340Z",
        updatedAt: "2021-04-08T04:05:30.340Z",
        "projects": [
            {
                "_id": "5a2ca2227c42ad6768274343",
                "name": "ABC",
                "departmentId": "5a2ca2227c42ad6768271232",
                createdAt: "2021-04-08T04:05:30.340Z",
                updatedAt: "2021-04-08T04:05:30.340Z",
            },
            {
                "_id": "5a2ca2227c42ad6768274344",
                "name": "XYZ",
                "departmentId": "5a2ca2227c42ad6768271232",
                createdAt: "2021-04-08T04:05:30.340Z",
                updatedAt: "2021-04-08T04:05:30.340Z",
            },
            {
                "_id": "5a2ca2227c42ad6768274345",
                "name": "BCA",
                "departmentId": "5a2ca2227c42ad6768271232",
                createdAt: "2021-04-08T04:05:30.340Z",
                updatedAt: "2021-04-08T04:05:30.340Z",
            }
        ]
    },
    {
        "_id": "5a2ca2227c42ad6768271233",
        "name": "Finance",
        "userId": "5a2ca2227c42ad67682731d4",
        createdAt: "2021-04-08T04:05:30.340Z",
        updatedAt: "2021-04-08T04:05:30.340Z",
        "projects": [
            {
                "_id": "5a2ca2227c42ad6768274346",
                "name": "DSE",
                "departmentId": "5a2ca2227c42ad6768271233",
                createdAt: "2021-04-08T04:05:30.340Z",
                updatedAt: "2021-04-08T04:05:30.340Z",
            },
            {
                "_id": "5a2ca2227c42ad6768274347",
                "name": "ADB",
                "departmentId": "5a2ca2227c42ad6768271233",
                createdAt: "2021-04-08T04:05:30.340Z",
                updatedAt: "2021-04-08T04:05:30.340Z",
            },
            {
                "_id": "5a2ca2227c42ad6768274348",
                "name": "QAW",
                "departmentId": "5a2ca2227c42ad6768271233",
                createdAt: "2021-04-08T04:05:30.340Z",
                updatedAt: "2021-04-08T04:05:30.340Z",
            }
        ]
    }
]
}

我正在努力解决的情况是,我必须根据用户 ID 显示最近添加的项目,但由于用户与项目没有直接关系,我正在努力寻找一种方法来查询最近添加的前 3 名基于用户 ID 的项目,即"_id": "5a2ca2227c42ad67682731d4"

我一般查询直接关系的方法是

export async function getProjectsByDepartmentId (
  req: Request,
  res: Response
): Promise<any> {
  try {
    const query = {
      departmentId: req.query.departmentId,
    };
    const aggregators = [];
    aggregators.push({
      $facet: {
        data: [
          { $match: query },
          { $sort: { _id: -1 } },
          { $limit: req.query.limit },
        ],
        total: [{ $count: "count" }],
      },
    });

    const projects = await Project.aggregate(aggregators);
    return res.status(200).send(projects);
  } catch (err) {
    return res.status(500).send(err || err.message);
  }
}

我期待的输出是

{
    "_id": "5a2ca2227c42ad67682731d4", // this is user id
    "name": "XYZ Bank",
    createdAt: "2021-04-08T04:05:30.340Z",
    updatedAt: "2021-04-08T04:05:30.340Z",
    "projects": [
                {
                    "_id": "5a2ca2227c42ad6768274343",
                    "name": "ABC",
                    "departmentId": "5a2ca2227c42ad6768271232",
                    createdAt: "2021-04-08T04:05:30.340Z",
                    updatedAt: "2021-04-08T04:05:30.340Z",
                },
                {
                    "_id": "5a2ca2227c42ad6768274344",
                    "name": "XYZ",
                    "departmentId": "5a2ca2227c42ad6768271232",
                    createdAt: "2021-04-08T04:05:30.340Z",
                    updatedAt: "2021-04-08T04:05:30.340Z",
                },
                {
                    "_id": "5a2ca2227c42ad6768274345",
                    "name": "BCA",
                    "departmentId": "5a2ca2227c42ad6768271232",
                    createdAt: "2021-04-08T04:05:30.340Z",
                    updatedAt: "2021-04-08T04:05:30.340Z",
                }
            ]
    ]
}

但不知道如何根据没有直接关系的 userId 查询项目。我怎样才能做到这一点?感谢您的建议

【问题讨论】:

  • 您应该在项目级别添加 createdAt 和 updatedAt,如果您可以添加 createdAt 和 updatedAt,我们将能够通过 createdAt 找到,我们可以通过聚合框架轻松找到
  • @Indraraj26 我在架构中都创建了带时间戳的 createdAt 和 updatedAt:true 但我想这将有助于按顺序查询文档,但我遇到的问题是我想通过用户 id 查询项目'没有直接关系

标签: node.js mongodb mongoose document


【解决方案1】:

您将用ObjectId() 包装它的_id,并用ISODate('') 包装它createAt。我不知道为什么它在 mongoplayground 中不起作用

db.collection.aggregate([
  {
    $match: {
      _id: "5a2ca2227c42ad67682731d4"
    }
  },
  {
    $unwind: "$departments"
  },
  {
    $unwind: "$departments.projects"
  },
  {
    $match: {
      "departments.projects.createdAt": {
        $gte: "2021-04-09T00:00:00Z"
      }
    }
  }
])

MongoPlayground:https://mongoplayground.net/p/Qll_t6RBltL

【讨论】:

  • 感谢您的快速帮助。我现在就试试
  • 你能检查我更新的问题吗?我已经添加了预期。我期待直接在用户下的项目
  • 我用你的方法解决了这个问题。我不知道我们可以使用点符号和项目信息以任何我们想要的方式轻松填充嵌套关系。我完全按照您的方法使用了投影,然后对数据进行了排序
猜你喜欢
  • 1970-01-01
  • 2016-07-20
  • 2018-03-09
  • 1970-01-01
  • 2014-08-05
  • 2021-02-25
  • 2016-08-16
  • 1970-01-01
相关资源
最近更新 更多