Conditional field projection

Is there a way to make it so that a field is not projected at all if a certain condition is not met?

Example:

 "productsData": {
        "totalPrice": "0",
        "totalPriceBeforeModifiers": "0",
        "count": 0,
        "products": []
    },

Because the value of the field count is 0, products should not be projected.

Hi @Vladimir,

Not sure if the following suits your use case, I’ve only tested it on the 2 sample documents in my own test environment (One document with a count value of 1 and the other document with a count value of 0

myFirstDatabase> db.data.find()
[
  {
    _id: ObjectId("6420f52f85731f19c94ceb58"),
    productsData: {
      totalPrice: '0',
      totalPriceBeforeModifiers: '0',
      count: 0,
      products: []
    }
  },
  {
    _id: ObjectId("6420fabe85731f19c94ceb59"),
    productsData: {
      totalPrice: '0',
      totalPriceBeforeModifiers: '0',
      count: 1,
      products: [ 'testproduct' ]
    }
  }
]

Aggregation used:

myFirstDatabase> db.data.aggregate({
  '$set': {
    'productsData.products': {
      '$cond': [
        { '$eq': [ '$productsData.count', 0 ] },
        '$$REMOVE',
        '$productsData.products'
      ]
    }
  }
})

Output:

[
  {
    _id: ObjectId("6420f52f85731f19c94ceb58"),
    productsData: { totalPrice: '0', totalPriceBeforeModifiers: '0', count: 0 }
  },
  {
    _id: ObjectId("6420fabe85731f19c94ceb59"),
    productsData: {
      totalPrice: '0',
      totalPriceBeforeModifiers: '0',
      count: 1,
      products: [ 'testproduct' ]
    }
  }
]

I believe you could use a similar form with $project instead of $set for the same output but the main thing here would be the following operators / variables:

If you’re having trouble with the $project stage with $cond, let me know what you’ve tried and the output / errors you’re getting.

Hope this helps.

Regards,
Jason

2 Likes

Thank you very much!

1 Like

This may be a bit simplistic but why not simply $match on “count” > 0 at the beginning of your pipeline

{ $match: { "count ": { $gt : 0}}}

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.