$lookup on ObjectId's in an array

后端 未结 6 1798
忘了有多久
忘了有多久 2020-11-22 04:53

What\'s the syntax for doing a $lookup on a field that is an array of ObjectIds rather than just a single ObjectId?

Example Order Document:

{
  _id:          


        
6条回答
  •  半阙折子戏
    2020-11-22 05:18

    I have to disagree, we can make $lookup work with IDs array if we preface it with $match stage.

    // replace IDs array with lookup results
    db.products.aggregate([
        { $match: { products : { $exists: true } } },
        {
            $lookup: {
                from: "products",
                localField: "products",
                foreignField: "_id",
                as: "productObjects"
            }
        }
    ])

    It becomes more complicated if we want to pass the lookup result to a pipeline. But then again there's a way to do so (already suggested by @user12164):

    // replace IDs array with lookup results passed to pipeline
    db.products.aggregate([
        { $match: { products : { $exists: true } } },
        {
            $lookup: {
                from: "products",
                 let: { products: "$products"},
                 pipeline: [
                     { $match: { $expr: {$in: ["$_id", "$$products"] } } },
                     { $project: {_id: 0} } // suppress _id
                 ],
                as: "productObjects"
            }
        }
    ])

提交回复
热议问题