skip to Main Content

I am having 2 collections –

  1. Collection name is content

enter image description here

  1. Collection name is surveys

enter image description here

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


  1. 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.

    
    { 
      from: "content", 
      localField: "content._id", 
      foreignField: "_id", 
      as: "someField" 
    } 
    
    
    Login or Signup to reply.
  2. One option is:

    1. Using $lookup to get the data from content collection
    2. Merge the arrays using $mergeObjects and $indexOfArray. After the lookup, the content data is on someField array. This step finds the releant content from someField and put it inside the matching survey’s content item, under the key type. This step also removes someField.
    3. Format the result using $map. This step uses $map to iterate over the content array and format the data under type to contain only the wanted part.
    4. Save it back using $merge. This step saves the result back into the collection.
    db.surey.aggregate([
      {$lookup: {
          from: "content",
          localField: "content.content_id",
          foreignField: "_id",
          as: "someField"
      }},
      {$set: {
          someField: "$$REMOVE",
          content: {$map: {
              input: "$content",
              in: {$mergeObjects: [
                  "$$this",
                  {type: {
                      $arrayElemAt: [
                        "$someField",
                        {$indexOfArray: ["$someField._id", "$$this.content_id"]}
                      ]
                  }}
              ]}
          }}
      }},
      {$set: {content: {$map: {
              input: "$content",
              in: {$mergeObjects: ["$$this", {type: "$$this.type.type"}]}
      }}}},
      {$merge: {into: "surey"}}
    ])
    

    See how it works on the playground example

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search