我有两个收藏品。sources
[
{
"_id": "0001",
"name": "John Doe"
},
{
"_id": "0002",
"address": "123 Some Place"
},
{
"_id": "0003",
"phone": "5555555555"
}
]和connections
[
{
"_id": "0001.0002",
"_from": "0001",
"_to": "0002",
"probability": 0.8
},
{
"_id": "0002.0003",
"_from": "0002",
"_to": "0003",
"probability": 0.6
}
]我试图使用$graphLookup进行图遍历,以获得所有源连接的列表。这是我的代码:
db.sources.aggregate([
{
$match: {
'_id': '0001'
}
},
{
$graphLookup: {
from: 'connections',
startWith: '_id',
connectFromField: '_from',
connectToField: '_to',
maxDepth: 2,
depthField: 'numConnections',
as: 'destinations'
}
}
])这将返回空的destinations数组。我希望它包含两个记录(0002和0003)。
另外,我希望在遍历过程中将概率乘以,使0001 -> 0002 = 0.8和0001 -> 0003 = 0.48 (0.8 * 0.6)。在这里,我一定遗漏了一些简单的东西,因为我已经尝试了在文档(https://docs.mongodb.com/manual/reference/operator/aggregation/graphLookup/)中准确地描述它的方式。
发布于 2017-12-04 18:55:16
您可以尝试以下查询。
您将需要两个$graphlookup,一个用于每个源的连接,另一个用于计算每个连接的概率。
$unwind与$graphlookup一起获取每个连接的所有概率。
$group对具有各自连接及其概率的源文档进行分组。
db.sources.aggregate([
{
"$match": {
"_id": "0001"
}
},
{
"$graphLookup": {
"from": "connections",
"startWith": "$_id",
"connectFromField": "_to",
"connectToField": "_from",
"maxDepth": 2,
"depthField": "numConnections",
"as": "destinations"
}
},
{
"$unwind": "$destinations"
},
{
"$graphLookup": {
"from": "connections",
"startWith": "$destinations._to",
"connectFromField": "_from",
"connectToField": "_to",
"maxDepth": 2,
"as": "destinations.probabilities"
}
},
{
"$addFields": {
"destinations.probabilities": {
"$reduce": {
"input": "$destinations.probabilities.probability",
"initialValue": 1,
"in": {
"$multiply": [
"$$value",
"$$this"
]
}
}
}
}
},
{
"$group": {
"_id": "$_id",
"name": {
"$first": "$name"
},
"destinations": {
"$push": "$destinations"
}
}
}
])https://stackoverflow.com/questions/47578646
复制相似问题