Mongoose: Querying related object with parameters

140 views Asked by At

Imagine that I have a series of objects related to each other as follows: every object A-type has field b, that contains id of some instance of object B-type.

// example of A type
const a = {
  some: 'blablabla',
  b: ObjectId('...')
};

// example of B type
const b = {
  name: 'bla',
  surname: 'blabla'
}

Question: so, how can I get only those A-type instances in which field b contains B-type object with fields with special values?

For example: get only those instances of A-type that has field some contains lorem and related to B-type objects with name contains ipsum?

P.S. I have tried something like this:

A.find({ some: 'lorem', 'b.name': 'ipsum' });

... but it does not work.

P.P.S. I am not a back-end developer at all. But I have no choice :)

1

There are 1 answers

0
Tom Slabbaert On

What you want to do is is to use $lookup (which is the sql equivalent of join if you know that). to "join" the 2 collections. then you can query both objects like so:

db.a.aggregate([
  {
    $match: {
      some: "lorem"
    }
  },
  {
    "$lookup": {
      "from": "b",
      "let": {
        "bId": "$b"
      },
      pipeline: [
        {
          $match: {
            $expr: {
              $and: [
                {
                  $eq: [
                    "$$bId",
                    "$_id"
                  ]
                },
                {
                  $eq: [
                    "$name",
                    "ipsum"
                  ]
                }
              ]
            }
          }
        }
      ],
      "as": "B"
    }
  },
  {
    $match: {
      "B.0": {
        $exists: true
      }
    }
  }
])

Mongo Playground