NodeJS Mongodb和nodej查找并过滤嵌套对象

c3frrgcw  于 2022-11-03  发布在  Node.js
关注(0)|答案(1)|浏览(209)

首先这是我的Workspaces系列

[
    {
        "WorkspaceId": "er890we8rw98ro9we8rjower",
        "WorkspaceTitle": "My First Workspace",
        "WorkspaceOwner": "user1",
        "Pages": [
            {
                "PageId": "a1sd32as7d841a23sd",
                "PageMembers": [
                    {
                        "MemberId": "user1",
                        "MemberName": "John",
                        "MemberAvatar": "https://example.com/jKLa29Wqy",
                        "MemberAccess": "can edit"
                    },
                    {
                        "MemberId": "user2",
                        "MemberName": "Margot",
                        "MemberAvatar": "https://example.com/wKKLSAqy",
                        "MemberAccess": "can edit"
                    },
                    {
                        "MemberId": "user3",
                        "MemberName": "Silvia",
                        "MemberAvatar": "https://example.com/wKKLSAqy",
                        "MemberAccess": "can edit"
                    },
                    ...
                ]
            }
        ]
    }
]

我想从文档中打印特定的嵌套对象。我需要像这样在我的集合中获得一个特定的文档。

{
  "WorkspaceId": "er890we8rw98ro9we8rjower",
  "WorkspaceTitle": "My First Workspace",
  "WorkspaceOwner": "user1",
  "Pages": [
    {
      "PageId": "a1sd32as7d841a23sd",
      "PageMembers": [
        {
          "MemberId": "user1",
          "MemberName": "John",
          "MemberAvatar": "https://example.com/jKLa29Wqy",
          "MemberAccess": "can edit"
        }
      ]
    }
  ]
}

但是当我运行这个脚本的时候,我的api会打印出所有的集合,我该怎么做呢?
下面是我使用的查询:

db.findOne({ $or: [{ "WorkspaceOwner": member_id }, { "Pages.PageMembers.MemberId": member_id }] }, function (err, result) {
            res.status(200).json(result);
});
h9a6wy2h

h9a6wy2h1#

可以通过使用展开和筛选器聚合来实现。

db.collection.aggregate([
  {
    "$unwind": "$Pages"
  },
  {
    $addFields: {
      "Pages.PageMembers": {
        $filter: {
          input: "$Pages.PageMembers",
          as: "temp",
          cond: {
            $in: [
              "$$temp.MemberId",
              [
                "user1"
              ]
            ]
          }
        }
      }
    }
  }
])

Playground

相关问题