Home > Blockchain >  How to filter $lookup result in mongodb
How to filter $lookup result in mongodb

Time:05-09

I have a two collections:

users: [
    {
        name: 'John',
        children: ["Mary"]
    },
    {
        name: 'Mary',
        children: []
    }
]

tokens: [
    {
        name: "someToken",
        owner: "John"
    }
]

I want to search by token name and returns users by owner and all childs of that user. For example:

if (query value is 'someToken') then add to results John data from collection
if ('John' has childs) then add to results him children

My tries:

$project

$pipeline

These ones return all users. No mater what is a query value is,

CodePudding user response:

You may consider starting the aggregation from token. Perform a $match by your query value, then perform the $lookup

db.tokens.aggregate([
  {
    $match: {
      name: "someTokenName"
    }
  },
  {
    "$lookup": {
      "from": "users",
      "localField": "owner",
      "foreignField": "name",
      "as": "usersLookup"
    }
  },
  {
    $project: {
      name: "$owner",
      children: {
        "$reduce": {
          "input": "$usersLookup.children",
          "initialValue": [],
          "in": {
            "$concatArrays": [
              "$$value",
              "$$this"
            ]
          }
        }
      }
    }
  }
])

Here is the Mongo playground for your reference.

  • Related