Wednesday, 3 May 2017

how to write a query which compares two fields with $lookup

users collection

[   
    {name: "alex", age: 25, surname: "brown"},
    {name: "tom", age: 34, surname: "gray"},
    {name: "alex", age: 65, surname: "red"},
    {name: "alex", age: 32, surname: "yellow"}
]

participation collection

[   
    {name: "alex", age: 32}
]

I want to get only one document's details whose name is alex and age is 32.

What have I done so far?

db.participation.aggregate([
   {$lookup: "users" , foreignField: "name" , localField: "name", as: "document"},
   {$unwind: "document"},
   {$match: {age: "$document.age"}}
])

But this returns nothing, the returned array is empty.

So how should I create the query?



via mmu36478

No comments:

Post a Comment