0
votes

I have a nested array. How can I use mongo aggregation query to get back documents, only if nested array elements has certain field and value. For example, consider this:

[
  {
    _id: 1,
    timezone: "America/New_York",
    message: "Step 1: Started",
    details: [
      {
        name: "A",
        date: "2017-02-08T12:10:40.787",
        location: "BLR11"
      },
      {
        name: "B",
        date: "2017-09-09T12:10:40.787",
        location: "BLR12"
      }
    ]
  },
  {
    _id: 2,
    message: " Step 1: Ended ",
    details: [
      {
        name: "E",
        date: "2017-05-08",
        location: "BLR31"
      }
    ]
  },
  {
    _id: 3,
    date: "2017-02-09",
    timezone: "Europe/London",
    message: "Step 2: Started",
    details: [
      {
        name: "E",
        date: "2017-05-08",
        location: "BLR11"
      }
    ]
  },
  {
    _id: 4,
    date: "2017-02-09T03:35:02.055",
    timezone: "+0530",
    message: "Step 2: In Progress"
  }
]

I want documents, which has location: "BLR11" in any of the array elements.

So with the above example, it should return back just documents with _id:1 and _id:3.

How can I do this with aggregation?

1

1 Answers

1
votes

You can use the dot notation to query an array's property:

db.collection.find({"details.location": "BLR11"})

Mongo Playground