graphLookup does not return documents in order

Hi Team,
I was just checking graphLookup to retrieve all links.
For example I have this data
A1->A2->A3->A4->A5 where A1 is in one collection and link between Ai to Aj is in another collection.
So when I ran the graphLookup queries It returns me all the links but did not return me in the above mentioned order It returned inthis order [A1, A3, A2, A5, A4]
I can write the logic to bring this into correct order but if there is any settings to return in correct order would be helpful.

Thanks,
Gheri.

Hi @Gheri_Rupchandani,

Can you please share the query and aome sample documents?

Best
Pavel

Hey Pavel,
I have two collections one objects and other links.
objects have { _id: “”, name: …}
And Links have {_id: , sourceObjectId:“id of object”, targetObjectId: “id of object”}
Summary objects collections storing domain objects and links storing relationships between objects
Thanks,
Gheri.

Hi @Gheri_Rupchandani,

I will still need the graphlookup code and the database version you are running on…

Best
Pavel

db.objects.aggregate(
{$match: {"_id": “0FbpzNkY6N48PYXBDZOCD” }},
{ graphLookup: { from: "links", startWith: "_id",
connectFromField: “targetId”,
connectToField: “sourceId”,
as: “linksData” } }).pretty()

Database version–> version() --> 4.4.1

Hi @Gheri_Rupchandani,

I see what you mean now. $graphLookup gurantee that the documents returned the treversed documents by your start and following the connection rules.

However it does not guarantee that returned in as field following that order or any order.

See the “as” comment.

If you wish to get it back in the wanted order sort them in next stage by the added depthField you need to specify.

Best
Pavel

1 Like

Sounds great,
It works
db.assets.aggregate({$match: {"_id": “0FbpzNkY6N48PYXBDZOCD” }},{ graphLookup: { from: "links", startWith: "_id", connectFromField: “targetId”, connectToField: “sourceId”, as: “linksData”, depthField: “level” } }, {$unwind: “$linksData”}, {$sort: {“linksData.level”:1}}, {group: {_id:"_id", linksData: {$push:"$linksData"}}}).pretty()
I guess it would work with 50 level deep graph assuming I have considered all memory limitations of graphLookup
Thanks,
Gheri.

1 Like