Jan
Jan

Reputation: 77

Using a where on an array with id's inside aggregate mongodb

Hi im really struggling finding a solution to this.

Im trying to see if an array contains a value that I give

I want all tickets of a specific organization.

The organization is saved in the user (Creator) in an array named organizations.

Models

ticket {
    creator: "ObjectId"
}

user {
    organizations: ["ObjectId", "ObjectId"]
}

This is what I have now

    Ticket.aggregate([
        {
            "$lookup": {
                "from": User.collection.name,
                "localField": "creator",
                "foreignField": "_id",
                "as": "creator"
            }
        },
        { "$unwind": "$creator" },
        { "$match": { "creator.organizations": {
            "$elemMatch": {"$in": ["60a77d5b57d8c960829a0343"]}}}
        },
        { "$set": {"creator": "$creator._id"}},
    ])

This doesn't work tho

I read that you can't use $elemMatch inside an aggregate because its a query. How do I achieve this? I've seen people saying to use a $filter but I have no clue how to make that.

Upvotes: 1

Views: 39

Answers (1)

Lahiru Tennakoon
Lahiru Tennakoon

Reputation: 649

$elemMatch is not required here. This can be achieved only using $match as shown below.

const mongoose = require("mongoose");

Ticket.aggregate([{
    "$lookup": {
      "from": User.collection.name,
      "localField": "creator",
      "foreignField": "_id",
      "as": "creator"
    }
  },
  {
    "$unwind": "$creator"
  },
  // Modified code
  {
    "$match": {
      "creator.organizations": mongoose.Types.ObjectId("60a77d5b57d8c960829a0343")
    }
  },
  {
    "$set": {
      "creator": "$creator._id"
    }
  },
])

Upvotes: 1

Related Questions