【问题标题】:Parent child reversal in the result结果中的父子反转
【发布时间】:2018-10-04 14:16:34
【问题描述】:

我正在使用 MongoDB 3.4。

有2个收藏如下。

集合 1:- 类型

{
  "_id": {
    "$numberLong": "1234"
  },
  "name" : "board1"
  "type" : "electronic"
},
{
  "_id": {
    "$numberLong": "1235"
  },
  "name" : "board2",
  "type" : "electronic"
}

系列 2:- 产品

{
  "_id": {
    "$numberLong": "9876"
  },
  "types" : [
     "1234",
     "1235",
     "1238"
   ]
},
{
  "_id": {
    "$numberLong": "9875"
  },
  "types" : [
     "1234",
     "1238"
   ]
}

类型集合会有多种类型,产品集合中的每个产品都有多种类型。

类型集合中的同一类型可以有多个具有不同 id 的文档。并且,产品集合可能具有具有相同类型或不同类型的不同 Id 的类型数组。

我想获取电子类型的所有 id,并在每个产品的类型数组中找到具有 id 的产品。

我想要下面这样的结果。

{
  "_id": {
    "$numberLong": "1234"
  },
  "name" : "board1",
  "products" : [
     "9876",
     "9875"
   ]
},
{
  "_id": {
    "$numberLong": "1235"
  },
  "name" : "board2"
  "products" : [
     "9876",
     "9875"
   ]
}

目前,我打了很多电话,比如为每个类型 id 获取所有产品。

有没有其他使用 $lookup 或任何其他机制的单一查询的简单方法?

【问题讨论】:

    标签: mongodb aggregation-framework


    【解决方案1】:

    您可以在 mongodb 3.6 及更高版本中尝试以下聚合

    db.types.aggregate([
      { "$match": { "type" : "electronic" }},
      { "$lookup": {
        "from": "testCollection2",
        "let": { "typeId": "$_id" },
        "pipeline": [
          { "$match": { "$expr": { "$in": ["$$typeId", "$types"] }}}
        ],
        "as": "products"
      }},
      { "$addFields": {
        "products": "$products._id"
      }}
    ])
    

    您可以在 mongodb 3.4

    中尝试以下聚合
    db.types.aggregate([
      { "$match": { "type" : "electronic" }},
      { "$lookup": {
        "from": "testCollection2",
        "localField": "_id",
        "foreignField": "types",
        "as": "products"
      }},
      { "$addFields": {
        "products": "$products._id"
      }}
    ])
    

    【讨论】:

    • 我刚用 3.6 试过,效果很好。 mongo 3.4版有什么吗?
    【解决方案2】:

    在 MongoDB 3.4 中,您可以使用 $lookup$addFieldsproducts 获取 _id

    db.types.aggregate([
        {
            "$match": { "type" : "electronic" }
        },
        {
            $lookup: {
                from: "products",
                localField: "_id",
                "foreignField": "types",
                "as": "products"
            }
        },
        {
            $project: {
                field1: 1,
                field2: 1,
                products: {
                    $map: {
                        input: "$products",
                        as: "p",
                        in: "$$p._id"
                    }
                }
            }
        }
    ])
    

    【讨论】:

    • 如何添加投影,因为我只需要类型集合中的特定文件?
    • 您可以将 $addFields 更改为 $project 并使用 1 将字段保留在结果集中
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-07
    • 1970-01-01
    • 2012-05-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多