fguillen
fguillen

Reputation: 38888

MongoDB how to select only specific sub_elements for a document?

In MongoDB I have documents like this:

{
  "_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
    }
  ]
}

And I would like to make a query by "created_at" but for each document in the result only returning the demographics elements which key are "age" or "gender".

I am trying combinations of $unwind and $project but I can not obtain any proper result.

I am expecting results as this:

# 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
    }
  ]
}

Upvotes: 0

Views: 56

Answers (1)

SuleymanSah
SuleymanSah

Reputation: 17898

You can use $filter aggregation after you match by created_at field.

$filter selects a subset of an array to return based on the specified condition and returns an array with only those elements that match the condition.

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

Upvotes: 1

Related Questions