1

I solved the same problem the author of this question had with the solution the other guy posted as an answer: Unwind empty array in mongodb

These days i updated my mongodb/mongoose and now i am getting an error:

MongoError: The top-level _id field is the only field currently supported for exclusion

It seems like mongo tries to "exclude" this field from the project now because of the 0 value.

I need to add an array with an object with {value:0} because otherwise this object will be ignored after the unwind.

  { $match: parameter},
  { $unwind : "$items" },
  { $project: {
    itemName: '$items.name'},
    itemValue : "$items.value",
    discount : { $cond : [ { $eq : ["$items.discounts", [] ]}, [ { value : 0} ], '$items.discounts'] } 
  }},  
  { $unwind: "$discount"},

Is there any other/newer solution to this problem? Thanks for your help.

1
  • Can you edit your question to include some sample documents for testing and the expected output from those documents? Commented Sep 9, 2016 at 6:58

1 Answer 1

0

I don't really understand your problem, first i would change the aggregation to :

{ $match: parameter},
  { $unwind : "$items" },
  { $project: {
    itemName: '$items.name'},
    itemValue : "$items.value",
    discount : { $cond : [ { $eq : ["$items.discounts", []}, [ null ], '$items.discounts'] } 
  }},  
  { $unwind: "$discount"}

The above works for me. I would advise you to try it with your favorite editor or in mongoshell and check if it's working.

Sign up to request clarification or add additional context in comments.

Comments

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.