I am having 2 collections –
- Collection name is content
- Collection name is surveys
I actually want to add the "type" information from the content collection to every content in every survey in the "surveys" collection.
I know in SQL we have to join these 2 tables first on _id and content_id commun columns and then add type column to suryeys table but not sure how should i do it here. I want the type value from content collection to add in every content field inside surveys collection. Please help me.
2
Answers
In mongoose (I assume you could be using mongoose, sind you added the tag) you can specify the relation in Schema definition and just just populate to add these fields to the output.
If you are not using mongoose you can use $lookup (https://www.mongodb.com/docs/manual/reference/operator/aggregation/lookup/) in your aggregation pipeline.
One option is:
$lookup
to get the data fromcontent
collection$mergeObjects
and$indexOfArray
. After the lookup, thecontent
data is onsomeField
array. This step finds the releantcontent
fromsomeField
and put it inside the matching survey’s content item, under the keytype
. This step also removessomeField
.$map
. This step uses$map
to iterate over thecontent
array and format the data undertype
to contain only the wanted part.$merge
. This step saves the result back into the collection.See how it works on the playground example