Home > Back-end >  Mongoose Unilevel Query
Mongoose Unilevel Query

Time:03-01

How can I do unilevel query with mongoose.

Example collection :

ID NAME PARENT ID
1 Alex 0
2 Michael 1
3 George 2
4 Yuri 1

Example output :

[{ id:1, name:Alex, parentId:0},{ id:2, Michael, parentId:1},{ id:3, name:George, parentId:2},{ id:4, name:Yuri, parentId:1}]

Thanks for helps.

CodePudding user response:

I don't completely understand the challenge, but I thought this might help, or maybe just a start. The output is a bit "raw", but more stages could be added to the pipeline to customize it.

db.collection.aggregate([
  {
    // start with somebody, or in this case
    // somebody's parentId
    "$match": {
      "parentId": 2
    }
  },
  {
    // go all the way up the parent tree
    "$graphLookup": {
      "from": "collection",
      "startWith": "$parentId",
      "connectFromField": "parentId",
      "connectToField": "_id",
      "depthField": "depth",
      "as": "parents"
    }
  }
])

Example output:

[
  {
    "_id": 3,
    "name": "George",
    "parentId": 2,
    "parents": [
      {
        "_id": 2,
        "depth": NumberLong(0),
        "name": "Michael",
        "parentId": 1
      },
      {
        "_id": 1,
        "depth": NumberLong(1),
        "name": "Alex",
        "parentId": 0
      }
    ]
  }
]

Try it on mongoplayground.net.

  • Related