2

I have an array called group containing a list of IDs, I have the find and populate statement below which works perfectly with this and I use populate to get the additional data - query below:

var stories = await Story .find( { 'group' : { $in : group } } ) .populate('group') .populate('createdBy') .sort('-created') 

I have an aggregate query (below) which does what I want but 1) it does not use the values in the group array, it simply returns all of the content, and 2) I don't get the additional data for the group and createdBy fields as I do for the find above.

var spellings = await Spelling.aggregate([ { "$sort": { "keyStageLevel": 1, "spellingLevel": 1 } }, { "$group" : { "_id": { "keyStageLevel": "$keyStageLevel", "class": "$class" }, "data": { "$push": { "spellingLevel": "$spellingLevel", "class": "$class", "name": "$name", "spellings": "$spellings", "created": "$created", "_id": "$_id", "group": "$group", "createdBy": "$createdBy" } } }}, { "$sort": { "_id": 1 } } ]) 

Edit - here is an example spelling document:

 { "_id":"5b1ff6f62bb1894efcf76ea0", "spellings":["here","are","spellings"], "name":"withclass", "group":"5ab79a639083cf35339b880a", "createdBy":"5ab79185d47b833506ff94b1", "created":"2018-06-12T16:38:14.571Z", } 

Can anyone help with how to use the values in the group array in my aggregate statement and how I can add in the additional data for the group and createdBy fields as I do for the find ?

2
  • you need to use $lookup aggregation stage which easily populate your group and createdBy... which mongodb version do you have? Commented Jun 12, 2018 at 20:44
  • Thanks @Ashish, I'm on v 3.6.3 Commented Jun 12, 2018 at 20:48

1 Answer 1

3

You can try below $lookup aggregation to populate the group and the createdBy field

var spellings = await Spelling.aggregate([ { "$match": { "group": { "$in": group }}}, { "$sort": { "keyStageLevel": 1, "spellingLevel": 1 } }, { "$lookup": { "from": CreatedBy.collection.name, "let": { "createdBy": "$createdBy" }, "pipeline": [ { "$match": { "$expr": { "$eq": [ "$_id", "$$createdBy" ] } } } ], "as": "createdBy" }}, { "$lookup": { "from": Group.collection.name, "let": { "group": "$group" }, "pipeline": [ { "$match": { "$expr": { "$eq": [ "$_id", "$$group" ] } } } ], "as": "group" }}, { "$unwind": "$group" }, { "$unwind": "$createdBy" }, { "$group" : { "_id": { "keyStageLevel": "$keyStageLevel", "class": "$class" }, "data": { "$push": { "spellingLevel": "$spellingLevel", "class": "$class", "name": "$name", "spellings": "$spellings", "created": "$created", "_id": "$_id", "group": "$group", "createdBy": "$createdBy" } } }}, { "$sort": { "_id": 1 } } ]) 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.