Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in SQL by (320 points)

I have the following schema in my taxon collection :

  "_id": 1, 

  "na": [ "root_1",

        "root_2",

        "root_3" ], 

  "pa": 1 

},{

  "_id": 2, 

  "na": [ "name_1", 

        "name_2", 

        "name_3"], 

  "pa": 1

},{

  "_id": 4, 

  "na": [ "otherName_1", 

        "otherName_2", 

        "otherName_3"],

  "pa": 2

}

Every document is related to another by the parent field, which corresponds to the _id of it's parent.

To the following result, recursive search is performed.

{ "_id": 4, 

  "nameList": [ "otherName_1",

              "name_1",

              "root_1"]

From document with a certain _id, get the first item of an array of each parent until document with _id: 1 is reached

I currently get this result by performing X queries (one by parent document, here 3 for example), but I'm pretty sure that this can be achieved using a single query. I already looked at the new $graphLookup operator, but couldn't manage to get my way with it...

Is it possible to achieve this in a single query using MongoDB 3.4.1?

Edit

I would run this for 50 documents each time, so the optimal solution would be to combine everything in a single query

for example, it would looks like

var listId = [ 4, 128, 553, 2728, ...];

var cursor = db.taxon.aggregate([

  {$match: 

     { _id: {$in: listId}}

  }, ...

)];  

and would output :

[{ "_id": 4, 

  "nameList": [ "otherName_1",

              "name_1",

              "root_1"]

}, { "_id": 128, 

  "nameList": [ "some_other_ame_1",

              "some_name_1",

              "root_1"]

}, { "_id": 553, 

  "nameList": [ "last_other_ame_1",

              "last_name_1",

              "root_1"]

} ... ]

Please log in or register to answer this question.

Related questions

0 votes
1 answer
asked Feb 17, 2021 in SQL by adhiraj (4k points)
0 votes
1 answer
+2 votes
1 answer

Browse Categories

...