0

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?

Arun Nalpet
  • 1,190
  • 1
  • 9
  • 20
  • 1
    Does this answer your question? [Find document with array that contains a specific value](https://stackoverflow.com/questions/18148166/find-document-with-array-that-contains-a-specific-value) – Captain Levi Jun 25 '20 at 18:52

1 Answers1

1

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

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

Mongo Playground

mickl
  • 48,568
  • 9
  • 60
  • 89
  • Wow! Thanks for the instant response! This is exactly the result I am looking for, but how can i achieve the same using aggregation pipeline? – Arun Nalpet Jun 25 '20 at 18:43
  • 1
    @ArunNalpet same query, just use `$match`: https://mongoplayground.net/p/kr52sy1690t – mickl Jun 25 '20 at 18:44
  • 1
    @micki Thanks that helped! I can add more operations to pipeline along with this! :) – Arun Nalpet Jun 25 '20 at 18:52