Westley
Westley

Reputation: 1153

How can I return a single property from an object in a mongoDB query?

I have a query that looks like this:

listProjectQry = [
    {
      $match: {
        city: city
      }
    },
    {
      $project: {
        _id: 0,
        rating: 1,
        title: 1,
        amenities: 1
      }
    }
  ]

This works fine but the amenities object actually maps to an array of amenity objects that themselves contain multiple fields. Right now I'm getting the entire array of amenities, but I'm wondering if I can make an array of just the IDs of the amenities and send that back down to the clients.

The intent is to make the query more performant and take less time. Maybe this optimization wouldn't help make it faster?

Upvotes: 2

Views: 1460

Answers (1)

mickl
mickl

Reputation: 49945

You can either use the dot notation:

{
    $project: {
        _id: 0,
        rating: 1,
        title: 1,
        "amenities._id": 1
    }
}

which will return an array of objects with one property _id or use $map to get an array of values

amenityIds: {
    $map: {
        input: "$amenities",
        in: "$$this._id"
    }
}

Upvotes: 1

Related Questions