MongoDB如何仅选择文档的特定sub_elements?

时间:2019-12-13 16:52:36

标签: mongodb aggregation-framework

在MongoDB中,我有这样的文档:

{
  "_id" : ObjectId("5cc9f3c87aa1024e079a3abf"),
  "created_at" : ISODate("2019-04-01T00:00:00.000Z"),
  "demographics" : [  
    {
      "key" : "gender",
      "value" : "male"
    }, 
    {
      "key" : "birth_year",
      "value" : 1992
    }, 
    {
      "key" : "city_or_rural",
      "value" : "rural"
    }, 
    {
      "key" : "car_purchase_intention",
      "value" : "no"
    }, 
    {
      "key" : "education_level",
      "value" : "high"
    }, 
    {
      "key" : "age",
      "value" : 26
    }
  ]
}

我想通过“ created_at”进行查询,但是对于结果中的每个文档,仅返回关键是“年龄”或“性别”的受众特征元素。

我正在尝试将$unwind$project组合使用,但无法获得任何适当的结果。

我期望这样的结果:

# 1
{
  "_id" : ObjectId("5cc9f3c87aa1024e079a3abf"),
  "created_at" : ISODate("2019-04-01T00:00:00.000Z"),
  "demographics" : [  
    {
      "key" : "gender",
      "value" : "male"
    }, 
    {
      "key" : "age",
      "value" : 26
    }
  ]
}

# 2
{
  "_id" : ObjectId("5cc9f3c87aa1024e079axxx"),
  "created_at" : ISODate("2019-04-01T00:00:00.000Z"),
  "demographics" : [  
    {
      "key" : "gender",
      "value" : "female"
    }, 
    {
      "key" : "age",
      "value" : 56
    }
  ]
}

1 个答案:

答案 0 :(得分:1)

通过created_at字段进行匹配后,您可以使用$filter聚合。

$filter根据指定的条件选择要返回的数组的子集,并返回仅包含那些与条件匹配的元素的数组。

db.collection.aggregate([
  {
    $match: {
      created_at: ISODate("2019-04-01T00:00:00.000Z")
    }
  },
  {
    $project: {
      created_at: "$created_at",
      demographics: {
        $filter: {
          input: "$demographics",
          as: "item",
          cond: {
            $in: [
              "$$item.key",
              [
                "gender",
                "age"
              ]
            ]
          }
        }
      }
    }
  }
])

Playground