pyborg
pyborg

Reputation: 166

MongDB: Query to extract dynamic key, value pair from nested documents

The below-given is my data structure, I have a requirement to extract "publishers" dynamic keys and compare ($lookup) with another collection for matching records, sum the % values.

 "_id" : ObjectId("5eff1e9a9bb60729d3278140"),
    "tracks" : [ 
        {
            "_id" : ObjectId("5efd9548327f5509b009b5a9"),
            "artist" : ["abc"],
            "genre" : "Pop",
            "publishers" : {
                "a" : "30.00%",
                "b" : "30.00%",
                "c" : "30.00%",
                "d" : "10.00%"
            },
            "__v" : 0
        }
  1. Is the data structure valid?
  2. I'm trying to convert this into $ObjectToArray but not able to convert the nested documents, any suggestions?

Upvotes: 0

Views: 702

Answers (1)

namar sood
namar sood

Reputation: 1590

You can use this aggregation pipeline. It will convert your dynamic keys in publishers array to an object of the following form, after that you can apply your $lookup stage easily.

  {
    "_id": ObjectId("5eff1e9a9bb60729d3278140"),
    "percentage": 30,
    "publisher": "b"
  }

db.collection.aggregate([
  {
    $unwind: "$tracks"
  },
  {
    $project: {
      publisher: {
        $objectToArray: "$tracks.publishers"
      }
    }
  },
  {
    $unwind: "$publisher"
  },
  {
    $project: {
      publisher: "$publisher.k",
      percentage: {
        $convert: {
          input: {
            $trim: {
              input: "$publisher.v",
              chars: "%"
            }
          },
          to: "double"
        }
      }
    }
  }
])

MongoDB Playground Ex. - 1


Updated example

MongoDB Playground Ex. - 2

Upvotes: 1

Related Questions