Populate Array of ObjectIds While Preserving Order

Hello @steffan, Welcome to the MongoDB community forum,

It will result documents in natural/stored order from the lookup collection.

You can do it by using $map and $filter operators after $lookup, but I can see you are doing $unwind and then the $group stage, also the $group stage does not preserve the order of documents!


I think you don’t need to $unwind here, see the below pipeline,

  {
    $lookup: {
      from: "guides",
      localField: "guides",
      foreignField: "_id",
      as: "guides_arr"
    }
  },
  {
    $lookup: {
      from: "sections",
      localField: "guides_arr.sections",
      foreignField: "_id",
      as: "sections_arr"
    }
  },
  {
    $addFields: {
      guides_arr: {
        $map: {
          input: "$guides_arr",
          as: "g",
          in: {
            $mergeObjects: [
              "$$g",
              {
                sections: {
                  $map: {
                    input: "$$g.sections",
                    as: "s",
                    in: {
                      $first: {
                        $filter: {
                          input: "$sections_arr",
                          cond: { $eq: ["$$s", "$$this._id"] }
                        }
                      }
                    }
                  }
                }
              }
            ]
          }
        }
      }
    }
  },
  {
    $addFields: {
      guides: {
        $map: {
          input: "$guides",
          as: "g",
          in: {
            $first: {
              $filter: {
                input: "$guides_arr",
                cond: { $eq: ["$$g", "$$this._id"] }
              }
            }
          }
        }
      }
    }
  },
  {
    $unset: [
      "guides_arr",
      "sections_arr"
    ]
  }

Playground

4 Likes