Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve null lookup entries on mongodb?

I have this query that provides me the join I want to:

db.summoners.aggregate([
    { "$match": { "nick":"Luispfj" } },
    { "$unwind": "$matches" },
    {
        "$lookup": {
            "from":"matches",
            "localField":"matches.gameId",
            "foreignField":"gameId",
            "as":"fullMatches"
        }
    },
    { "$unwind": "$fullMatches" },
    {
        "$group": {
            "_id": null,
            "matches": { "$push":"$fullMatches" }
        }
    }
])

But when I run the unwind function the null entries are gone. How do I retrieve them (with their respective "gameId"s, if possible?

Also, is there a way to retrieve only the matches array, instead of it being a subproperty of the "null-id-object" it creates?

like image 724
Luis Paulo Avatar asked Jul 13 '17 18:07

Luis Paulo


1 Answers

$unwind takes an optional field preserveNullAndEmptyArrays which by default is false. If you set it to true, unwind will output the documents that are null. Read more about $unwind

{ 
  "$unwind": {
    path: "$fullMatches",
    preserveNullAndEmptyArrays: true
  }
},
like image 190
Stubbies Avatar answered Oct 03 '22 22:10

Stubbies