Home > Net >  Equivalent to Mongoose `.populate` for ObjectIds in Array that maintains array order
Equivalent to Mongoose `.populate` for ObjectIds in Array that maintains array order

Time:08-03

What’s the MongoDB aggregation equivalent to Mongoose’s .populate on arrays? Specifically, I’m wondering if there’s anything that will a) perform the functionality of $lookup but b) still keep array order with the returned objects.

I.e., looking up the items in [ ObjectId(b), ObjectId(a), ObjectId(c) ] should return the array in the same order [ ItemB, ItemA, ItemC ], and not [ItemA, ItemB, ItemC] or any other permutation.

CodePudding user response:

One option is to use a regular $lookup and then order the results:

db.colA.aggregate([
  {$lookup: {
    from: "colB",
    localField: "data",
    foreignField: "_id",
    as: "newData"
  }},
  {$set: {
    newData: "$$REMOVE",
    data: {
      $map: {
        input: "$data",
        in: {$arrayElemAt: ["$newData", {$indexOfArray: ["$newData._id", "$$this"]}]}
        }
      }
    }
  }
])

See how it works on the playground example

  • Related