繁体   English   中英

如何在 MongoDB 中的对象“_id”之间连接两个 collections

[英]How join two collections between Objects "_id" in MongoDB

问候,我正在尝试合并两个 collections。

  • 产品

  • 类别

重点是它唯一的关系就是对应文档的ObjectId,见:

产品系列

{
    "_id": Object(607a858c2db9a42d1870270f),
    "code":"CODLV001",
    "name":"Product Name",
    "category":"607a63e5778bf40cac75d863",
    "tax":"0",
    "saleValue":"0",
    "status":true
}

类别集合

{
    "_id": Object(607a63bf06e84e5240d377de),
    "name": "Diversey Care",
    "status": true
},
{
    "_id": Object(607a63e5778bf40cac75d863),
    "name": "Sani Tisu Profesional",
    "status": true
}

我在做什么

.collection(collection)
        .aggregate([
          {
            $lookup: {
              from: 'categories',
              localField: 'products.category',
              foreignField: 'categories._id',
              as: 'category',
            },
          },
        ])
        .toArray();

我得到了什么?

{
    _id: 607a858c2db9a42d1870270f,
    code: 'CODLV001',
    name: 'Product Name',
    category: [ [Object], [Object] ],
    tax: '0',
    saleValue: '0'
  }

我期待什么?

{
        _id: 607a858c2db9a42d1870270f,
        code: 'CODLV001',
        name: 'Product Name',
        category: [ [Object] ], // or every field from category collection without an array object
        tax: '0',
        saleValue: '0'
      }

但是,如果我使用这种方式,类别字段是一个空数组

{
$lookup: {
          from: 'categories',
          localField: 'category',
          foreignField: '_id', 
          as: 'category', 
        },
      },

那么,我做错了什么(以防万一我是 MongoDB 世界的新手)?

您的查询中几乎没有修复,

  • products集合字段category是字符串类型,而categories字段_id是 objectId 类型,所以我们需要使用$toObjectId将其转换为 objectId
  • $lookup ,将localField作为category传递,将foreignField作为_id传递,不需要 concat 集合名称
.collection(collection).aggregate([
  {
    $addFields: {
      category: {
        $toObjectId: "$category"
      }
    }
  },
  {
    $lookup: {
      from: "categories",
      localField: "category",
      foreignField: "_id",
      as: "category"
    }
  }
]).toArray();

操场

暂无
暂无

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

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