$lookup on ObjectId's in an array

后端 未结 6 1658
忘了有多久
忘了有多久 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:22

    You can also use the pipeline stage to perform checks on a sub-docunment array

    Here's the example using python (sorry I'm snake people).

    db.products.aggregate([
      { '$lookup': {
          'from': 'products',
          'let': { 'pid': '$products' },
          'pipeline': [
            { '$match': { '$expr': { '$in': ['$_id', '$$pid'] } } }
            // Add additional stages here 
          ],
          'as':'productObjects'
      }
    ])
    

    The catch here is to match all objects in the ObjectId array (foreign _id that is in local field/prop products).

    You can also clean up or project the foreign records with additional stages, as indicated by the comment above.

提交回复
热议问题