Reputation: 166
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
}
Upvotes: 0
Views: 702
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"
}
}
}
}
])
Upvotes: 1