Home > Back-end >  How to lookup object in array with aggregation in MongoDB?
How to lookup object in array with aggregation in MongoDB?

Time:02-11

I'm using aggregate([...]) method to select documents from MongoDB, but I have a problem with $lookup, I can't get the results of the reference field info after query, it not works because it always return empty array. How can i solve this problem ?

My MongoSchema config:

const PostModel = new Schema({
  ...,
  info: [
    {
      label: {
        type: ObjectId,
        ref: 'catalogs',
        required: true           
      },
      value: {
        type: ObjectId,
        ref: 'attributes', 
        required: true           
      }
    }
  ],
  ...
})

My code for execute aggregate to query collection:

  const doc = await PostModel.aggregate([    
    {
      "$lookup": {
        "from": "catalogs",  
        "localField": "info.label",  
        "foreignField": "_id",
        "as": "infoLabel"
      }
    },           
    {
      "$lookup": {
        "from": "attributes",  
        "localField": "info.value",  
        "foreignField": "_id",
        "as": "infoValue"
      }
    },                  
    {
      "$project": {
        info: {
          label: '$infoLabel',
          value: '$infoValue'
        }
      }
    }  
  ])

  console.log(doc) // it always return empty array :(

CodePudding user response:

You need to first unwind the info then use lookup query that will work

{ $unwind:"$info" }, { $lookup:{ ... } }

  • Related