1

Let's say that I have the following documents in a MongoDB collection (this is only a simplified version of my real data):

/* 1 */
{
    "_id" : "objectives/core/1001",
    "tmp" : [ 
        {
            "name" : "analysisType"
        }, 
        {
            "name" : "sampleFormat"
        }
    ]
}
/* 2 */
{
    "_id" : "objectives/core/1003",
    "tmp" : [ 
        {
            "name" : "analysisType"
        }
    ]
}
/* 3 */
{
    "_id" : "objectives/core/1004",
    "tmp" : []
}

Note that the last document has empty tmp array.

I wrote an aggregation query with Mongo 3.2 which "unwinds" tmp and preserves empty arrays:

db.entities.aggregate({ "$unwind" : { path: "$tmp", preserveNullAndEmptyArrays: true } } );

And here is my (desired) output:

/* 1 */
{
    "_id" : "objectives/core/1001",
    "tmp" : { "name" : "analysisType" }
}
/* 2 */
{
    "_id" : "objectives/core/1001",
    "tmp" : {
        "name" : "sampleFormat"
    }
}
/* 3 */
{
    "_id" : "objectives/core/1003",
    "tmp" : { "name" : "analysisType" }
}
/* 4 */
{ "_id" : "objectives/core/1004" }

However this won't work with older version of MongoDB, as they don't support preserveNullAndEmptyArrays attribute - their regular unwind operation (without that attribute) will not generate document number 4 from the above listing. Do you have any ideas how to implement this using Mongo3.0?

Lukasz
  • 7,572
  • 4
  • 41
  • 50

1 Answers1

3

you could add a project phase with conditional statement:

db.lx.aggregate([{
            $project : {
                "_id" : 1,
                "tmp" : {
                    $cond : {
                        if  : {
                            $eq : ["$tmp", []]
                        },
                    then : [null],
                    else  : "$tmp"
                }
            }
        }
    }, {
        "$unwind" : {
            path : "$tmp"
        }
    }
])
profesor79
  • 9,213
  • 3
  • 31
  • 52