0

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?

Jeffrey Kang
  • 77
  • 1
  • 8

2 Answers2

0

The query always returns a document, so you might not get the very specific result you need, you can search by the children code but ultimately the result will be a collection of document with children attribute.

However this can be achieved by aggregation

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

Not sure about the syntax but basic idea remain same.

Rahul Kumar
  • 2,781
  • 1
  • 21
  • 29
0

Can try it

db.CollectionName.aggregate([
  {$unwind : "$children"},
  {$match : {"children.code": {$in :[1,4,6]}}},
  {$project : {_id:0, code : "$children.code"}}
]);
Shaishab Roy
  • 16,335
  • 7
  • 50
  • 68