mongodb returns all fields instead of the matching ones

First of all your $lookup has a bad localField. Following your schema should be _id instead of groups_id.

The second thing is, what are you trying to join?

Knowing an _id get all peoplegroups which groupid is equal to _id? Or only group your peoplegroups by the same groupid?

To get the first one you need a $match stage before the $lookup like this:

db.group.aggregate([
  {
    "$match": {
      "_id": 1
    }
  },
  {
    "$lookup": {
      "from": "peoplegroups",
      "localField": "_id",
      "foreignField": "groupid",
      "as": "User"
    }
  }
])

In this way you will get all users with groupid equal to 1.

Example here

But, the second option (following your query), will group different users. Look this example to know how works.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top