Home > Net >  mongodb: How to build facets from an array of objects
mongodb: How to build facets from an array of objects

Time:02-24

What would be the best way to create facets from an array of objects with different attributes for each product.

Example Data:

[
  {
    "key": 1,
    "title": "Product A",
    "attrs": [
      {
        "keyasd": "size",
        "value": "small"
      },
      {
        "kedasy": "color",
        "value": "red"
      }
    ]
  },
  {
    "key": 2,
    "title": "Product B",
    "attrs": [
      {
        "key": "size",
        "value": "large"
      },
      {
        "key": "color",
        "value": "blue"
      }
    ]
  },
  {
    "key": 3,
    "title": "Product C",
    "attrs": [
      {
        "key": "resolution",
        "value": "8K"
      },
      {
        "key": "refresh rate",
        "value": "60 Hz"
      },
      
    ]
  }
]

The result I would like to get would be something like this:

[
    {
        "_id": {
            "key": "size",
            "values" : [
                {"title": "small", "count": 1},
                {"title": "large", "count": 1}
            ]
        }
    },
    {
        "_id": {
            "key": "color",
            "values" : [
                {"title": "red", "count": 1},
                {"title": "blue", "count": 1}
            ]
        }
    },
    {
        "_id": {
            "key": "resolution",
            "values" : [
                {"title": "8K", "count": 1}
            ]
        }
    },
    {
        "_id": {
            "key": "refresh rate",
            "values" : [
                {"title": "60 Hz", "count": 1}
            ]
        }
    }
]

I don't know if the result I put is possible, but I need to somehow build it, even if it's individually each facet for each type of attribute that a product can have

CodePudding user response:

db.collection.aggregate([
  {
    "$unwind": "$attrs"
  },
  {
    "$group": {
      "_id": {
        k: "$attrs.key",
        v: "$attrs.value"
      },
      "count": { "$sum": 1 }
    }
  },
  {
    "$group": {
      "_id": "$_id.k",
      "values": {
        "$push": {
          "title": "$_id.v",
          "count": "$count"
        }
      }
    }
  },
  {
    "$project": {
      "_id": {
        key: "$_id",
        values: "$values"
      }
    }
  }
])

mongoplayground

  • Related