0

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 :(
2
  • 1
    It would be helpful if you can provide some sample dataset and expected output Commented Feb 10, 2022 at 15:42
  • @ray thanks, i was solved my problem Commented Feb 10, 2022 at 17:36

1 Answer 1

1

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

{ $unwind:"$info" },
{ $lookup:{ ... } }
Sign up to request clarification or add additional context in comments.

3 Comments

I don't know how to grouping results after using $unwind
okey, i was solved my problem with $unwind. Thanks
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.