Search code examples
mongodbmongodb-queryaggregation-frameworkmongodb-.net-driver

MongoDB: Project to array item with minimum value of field


Suppose my collection consists of items that looks like this:

{
    "items" : [
        {
            "item_id": 1,
            "item_field": 10
        },
        {
            "item_id": 2,
            "item_field": 15
        },
        {
            "item_id": 3,
            "item_field": 3
        },
    ]
}

Can I somehow select the entry of items with the lowest value of item_field, in this case the one with item_id 3?

I'm ok with using the aggregation framework. Bonus point if you can give me the code for the C# driver.


Solution

  • You can use $reduce expression in the following way.

    The below query will set the initialValue to the first element of $items.item_field and followed by $lt comparison on the item_field and if true set $$this to $$value, if false keep the previous value and $reduce all the values to find the minimum element and $project to output min item.

    db.collection.aggregate([
        {
             $project:  {
                items: {
                    $reduce: {
                        input: "$items",
                        initialValue:{ 
                             item_field:{ 
                                $let: { 
                                    vars: { obj: { $arrayElemAt: ["$items", 0] } },
                                    in: "$$obj.item_field"
                                }
                            }
                        },
                        in: {
                              $cond: [{ $lt: ["$$this.item_field", "$$value.item_field"] }, "$$this", "$$value" ] 
                        }
                    }
                }
            }
        }
    ])