简体   繁体   English

Mongodb 根据 _id 从另一个集合中获取元素值

[英]Mongodb get element value from another collection based on its _id

I'm trying to get an element value based on a result _id in an aggregation.我正在尝试根据聚合中的结果 _id 获取元素值。

This is the aggregation:这是聚合:

$project: {
  _id: 0,
  brand: "$_id",
  "options": {
    $mergeObjects: "$ram"
  },
  sum: {
    $add: [
      "$sm",
      1
    ]
  }
}

And I want brand to get the name from other collection named "brands" which looks like this我希望品牌从其他名为“品牌”的集合中获取名称,如下所示

    [
  {
    "_id": ObjectId("617b0dbacda6cbd1a0403f68"),
    "SerialNumber": "45454234324",
    "name": "hp"
  },
  {
    "_id": ObjectId("617b0dbacda6cbd1a0403f69"),
    "SerialNumber": "azazz5245454az",
    "name": "asus"
  }]

What I want to get is the name of brand using using its _id based on the result _id.我想要得到的是使用基于结果_id 的_id 的品牌名称。 Using SQL its something like this:使用 SQL 它是这样的:

Get brands.name where _id=brands._id

i managed to do it using $lookup我设法使用 $lookup 做到了

{
                $lookup:
                {
                    from: "brands",
                    localField: "brand",
                    foreignField: "_id",
                    as: "brand"
                }
            },
            {
                $set: {
                    brand: "$brand.brand"     
                }
            },

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

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