Looking for some direction on how to construct a mongo query for a graph network visualization.
I have a data model that looks like this:
stories[
{
story: "story 1",
theme_ids: [1,2,3],
author_ids: [a,b,c]
},
{
story: "story 2",
theme_ids: [4],
author_ids: [a]
}
...
]
I would like the result of the query to grab all of the pairs of themes and authors like so:
[
{from: 1, to: a},
{from: 1, to: b},
{from: 1, to: c},
{from: 2, to: a},
{from: 2, to: b},
{from: 2, to: c},
{from: 3, to: a},
{from: 3, to: b},
{from: 3, to: c},
{from: 4, to: a}
]
Thank you! MongoDB v3.4
You can use double $unwind to get all pairs:
db.col.aggregate([
{
$project: {
from: "$theme_ids",
to: "$author_ids"
}
},
{
$unwind: "$from"
},
{
$unwind: "$to"
}
])
If you need to remove the duplicates you can add $group with $addToSet
:
{
$group: {
_id: null,
uniquePairs: { $addToSet: "$$ROOT" }
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.