Search code examples
mongodbnested-documents

How can I get children in nested documents with some conditions?


I have a collection :

{
    _id : ...
    children : [
        {
            code:0
        },

        {
            code:1
        },

        {
            code:2
        }
    ]
},

{
    _id : ...
    children : [
        {
            code:3
        },

        {
            code:4
        },

        {
            code:5
        }
    ]
},

{
    _id : ...
    children : [
        {
            code:6
        },

        {
            code:7
        },

        {
            code:8
        }
    ]
}

In this collection, I wanna get children width some code.

For example, if I want children coded 1, 4, 6, the result I need is:

{
    code:1
},

{
    code:4
},

{
    code:6
}

Every document has some children. Every child has a attribute code. How can I do this for this achievement?


Solution

  • Can try it

    db.CollectionName.aggregate([
      {$unwind : "$children"},
      {$match : {"children.code": {$in :[1,4,6]}}},
      {$project : {_id:0, code : "$children.code"}}
    ]);