Terminating graphlookup

42 views
Skip to first unread message

Conrad Mclean

unread,
May 22, 2017, 8:41:40 PM5/22/17
to mongodb-user
Hello All,

I'm pretty sure this is a NOOB question...

I have a series of origins and destinations... and need to get from point a to point b the quickest way...

eg.

a  to b
b to c
c to d
d to e
e to f
f to g
g to h
h to i
a to e

doing a graphlookup will give me two paths, the obvious a to i going thru all point and the a to i via a to e ... what I need to do however is terminate at g for example.. what are the routes from a to g... I have to know the dept to terminate using depth... i want to leverage Mongo to find the paths then look at depth to determine the shortest.  Thanks!

Rupa Narayanan

unread,
Jun 21, 2017, 5:58:35 PM6/21/17
to mongodb-user
Conrad,

You should be able to achieve the shortest path using $graphlookup with 'restrictSearchWithMatch' to terminate at g , $sort on the depthField  and $project to display the fields needed. Please find provided below a sample query and also you might find this MongoDB blog on $graphlookup to find the shortest path helpful.

db.route.insert({"origin":  "a","destination":  "b"})
db
.route.insert({"origin":  "b", "destination":  "c"})
db
.route.insert({"origin":  "c", "destination":  "d"})
db
.route.insert({"origin":  "d", "destination":  "e"})
db
.route.insert({"origin":  "e", "destination":  "f"})
db
.route.insert({"origin":  "f", "destination":  "g"})
db
.route.insert({"origin":  "g","destination":  "h"})
db
.route.insert({"origin":  "h","destination":  "i"})
db
.route.insert({"origin":  "a", "destination":  "e"})




db
.route.aggregate( [
   
{ $match:  { origin: { $eq: "a" } } },
   
{
      $graphLookup
: {
         
from: "route",
         startWith
: "$destination",
         connectFromField
: "destination",
         connectToField
: "origin",
         depthField
: "numConnections",
         
as: "traverseroute",
         restrictSearchWithMatch
:{"destination":{"$ne":"h"}}
     
}
   
},         { $sort: { 'traverseroute.numConnections': 1 }},
             
{  $project:  {"_id":0, "origin":1, "traverseroute.origin":1}}
   
])


This returns sorted result based on the traversed route

{ "origin" : "a", "traverseroute" : [ { "origin" : "f" }, { "origin" : "e" } ] }
{ "origin" : "a", "traverseroute" : [ { "origin" : "f" },  { "origin" : "e" },{ "origin" : "d" }, { "origin" : "c" }, { "origin" : "b" } ] }



Regards,
Rupa
Reply all
Reply to author
Forward
0 new messages