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?

1

1 Answer 1

1

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

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

Mongo Playground

Sign up to request clarification or add additional context in comments.

3 Comments

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?
@ArunNalpet same query, just use $match: mongoplayground.net/p/kr52sy1690t
@micki Thanks that helped! I can add more operations to pipeline along with this! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.