Unwind for array of objects

Hi everyone! I have a collection ‘users’ which contains documents having fields ‘name’ and ‘schoolid’. I have another collection ‘schools’ ,which contains ‘schoolid’ and ‘name’ (schoolid is not mongodb generated objectid). Now I want output which will have ‘name’ from users and another field ‘school’ which will contain ‘name’ from schools collection corresponding to the schoolid. Basically I have to join these collections based on schoolid(I am not using REF so I cannot use .populate). I am able to do so by following code: db.user.aggregate([{ $lookup:{from:“schools”,as:“school”,let:{schoolid:"$schoolid"},pipeline:[{$match:{$expr:{$and:[{$eq:["$schoolid","$$schoolid"]}]}}},{$project:{name:1,_id:0}}]}},])
But in this output I am getting ‘school’ as an array, containing object with a key ‘name’ and then value as the school name from ‘schools’ collection. But instead I want ‘school’ as a normal string which will directly display the school name and not along with the key ‘name’. I tried to use unwind but it simply converts that array into object. Please help me with the same. Thank you

Please provide sample documents from both collections so that we can experiment with your data.

Also provide documents showing the expected result.

Hi steevej, Thanks for replying.
here are the collections:

  1. Users collection
    [{"_id": ObjectId
    “name”: “Nikita”
    “schoolid”: “1”},
    {_id: ObjectId
    “name”: “Sunita”
    “schoolid”: “2”}]

  2. Schools collection
    [{"_id": ObjectId
    “name”: “Sheel niketan”
    “schoolid”: 1},{"_id": ObjectId
    “name”: “Vidya sagar”
    “schoolid”: “2”}

3.Output I want
[{“name”: “Nikita”, “schoolname”:“Sheel niketan”},
{“name”: “Sunita”, “schoolname”:“Vidyasagar”}]

Please read Formatting code and log snippets in posts and format your data in a usable format.

1 Like