Answer a question

I am new to mongodb aggregation. my mongo document have many arrays. I need to export it as a flat file. For that I need structure it. I tried following aggregation:

[
{$unwind : "$items" },
{$unwind : "$items.discounts"},    
{$unwind : "$payments"},
{$unwind : "$payments.items"},  
{$unwind : "$payments.refunds"}
]

It worked, then i just added following condition to filter data

[
{$match : { "updatedtime": { $gt: 1514764800000}}},
{$unwind : "$items" },
{$unwind : "$items.discounts"},    
{$unwind : "$payments"},
{$unwind : "$payments.items"},  
{$unwind : "$payments.refunds"}
]

returns 0 rows, I tried again with match statement alone

[
{$match : { "updatedtime": { $gt: 1514764800000}}}
]

It Works again.

[
{$match : { "updatedtime": { $gt: 1514764800000}}},
{$unwind : "$items" }
]

Works.

[
{$match : { "updatedtime": { $gt: 1514764800000}}},
{$unwind : "$items" },
{$unwind : "$items.discounts"}
]

Not working. Can any one tell me is am doing something wrong. Is there any other way to do this?

Answers

If you $unwind an array field like items.discounts that's empty, the resulting output is no documents. To preserve these documents, enable the preserveNullAndEmptyArrays option of $unwind:

[
{$match : { "updatedtime": { $gt: 1514764800000}}},
{$unwind : "$items" },
{$unwind : {path: "$items.discounts", preserveNullAndEmptyArrays: true}}
]
Logo

MongoDB社区为您提供最前沿的新闻资讯和知识内容

更多推荐