1

let's say i have documents like this in my mongodb:

{
    id: 1,
    names: [
        {
            id: 2,
            first: [
                {
                    id: 3,
                    name: "alice",
                },
                {
                    id: 4,
                    name: "bob",
                }, 
            ]
        },
        {
            id: 5,
            first: [
                {
                    id: 6,
                    name: "berhe",
                },
                {
                    id: 7,
                    name: "belay",
                }, 
            ]
       }
    ]
}
{
    id: 8,
    names: [
        {
            id: 9,
            first: [
                {
                    id: 10,
                    name: "gemechu",
                },
                {
                    id: 11,
                    name: "samy",
                }, 
            ]
        },
        {
            id: 12,
            first: [
                {
                    id: 13,
                    name: "helen",
                },
                {
                    id: 14,
                    name: "natu",
                }, 
            ]
        }
    ]
}

now how to retrieve a value with

id=8, 
names.id = 9, 
names.first.id=10 

which is like this:

{
    id:10,
    name:"gemechu"
} 
turivishal
  • 34,368
  • 7
  • 36
  • 59
mokie-H
  • 15
  • 4
  • 1
    Does this answer your question? [Find in Double Nested Array MongoDB](https://stackoverflow.com/questions/29071748/find-in-double-nested-array-mongodb) – Avani Khabiya May 30 '21 at 12:49

1 Answers1

0
  • $match to filter documents by all conditions using $elemMatch,
  • $unwind deconstruct names array
  • $match names id condition
  • $unwind deconstruct first array
  • $match first id condition
  • $project to format result
db.collection.aggregate([
  {
    $match: {
      id: 8,
      names: {
        $elemMatch: {
          id: 9,
          "first.id": 10
        }
      }
    }
  },
  { $unwind: "$names" },
  { $match: { "names.id": 9 } },
  { $unwind: "$names.first" },
  { $match: { "names.first.id": 10 } },
  {
    $project: {
      id: "$names.first.id",
      name: "$names.first.name"
    }
  }
])

Playground

turivishal
  • 34,368
  • 7
  • 36
  • 59