简体   繁体   English

为什么在使用 $project 聚合 function 时重命名 mongodb 中的子对象数组中的字段返回数组?

[英]Why does renaming a field in a child array of objects in mongodb returning an array when using $project in aggregate function?

My query goes like this im using aggregate function with lookup:我的查询像这样使用聚合 function 进行查找:

this.document.aggregate([
  {
    $lookup : {
      from: "projects",
      localField: "_id",
      foreignField: "organization_id",
      as: "projects",
    }, 
  },
  {
    $lookup : {
      from: "accounts",
      localField: "accounts",
      foreignField: "_id",
      as: "organization_accounts",
    },
  },
  {
    "$project": {
      "_id" : false,
      "id": "$_id",
      "name": 1,
      "email": "$email",
      "projects.id": "$projects._id",
      "projects.name" : 1,
      "projects.organization_id" : 1,
      "organization_accounts._id" : 1,
      "organization_accounts.first_name" : 1,
      "organization_accounts.last_name" : 1,
      "organization_accounts.email" : 1,
      "organization_accounts.main_org_id" : 1,
    }
  }
])

But the output goes like this:但是 output 是这样的:

  "id": "5ec69acbc072871bb03dd773",
  "email": "organization email",
  "name": "Organization name",
  "projects": [
    {
      "name": "project 1",
      "organization_id": "5ec69acbc072871bb03dd773",
      "id": [
        "5ec6a08342ad5b0a28ba6876"
      ]
    }
  ],
  "organization_accounts": []

I've tried applying the solution from this question but it doesnt seem to work or idk.我已经尝试应用这个问题的解决方案,但它似乎不起作用或 idk。

The projects.id field should be a string not an array. projects.id 字段应该是字符串而不是数组。

PS: Just new to mongoDB PS:刚到 mongoDB

You have to $unwind the embedded arrays.您必须 $unwind 嵌入式 arrays。 You will get the cartesian product of array length for each document.您将获得每个文档的数组长度的笛卡尔积。 Example例子

this.document.aggregate([
  {
    $lookup : {
      from: "projects",
      localField: "_id",
      foreignField: "organization_id",
      as: "projects",
    }, 
  },
  {
    $lookup : {
      from: "accounts",
      localField: "accounts",
      foreignField: "_id",
      as: "organization_accounts",
    },
  },
  {
    "$project": {
      "_id" : false,
      "id": "$_id",
      "name": 1,
      "email": "$email",
      "projects.id": "$projects._id",
      "projects.name" : 1,
      "projects.organization_id" : 1,
      "organization_accounts._id" : 1,
      "organization_accounts.first_name" : 1,
      "organization_accounts.last_name" : 1,
      "organization_accounts.email" : 1,
      "organization_accounts.main_org_id" : 1,
    }
  },
   {
    $unwind: "$projects"
  },
  {
    $unwind: "$projects.id"
  }
])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM